且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用字符串按名称动态调用 Python 函数?

更新时间:2021-07-27 05:16:40

您可以使用 getattr 函数:

You can use the getattr function:

import torchvision

model_name = 'resnet18'
model = getattr(torchvision.models, model_name)(pretrained=configs.use_trained_models)

这基本上与点符号相同,只是在函数形式中接受字符串来检索属性/方法.

This essentially is along the lines the same as the dot notation just in function form accepting a string to retrieve the attribute/method.