如何使用字符串按名称动态调用 Python 函数? [英] How to call Python function by name dynamically using a string?
本文介绍了如何使用字符串按名称动态调用 Python 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的 Python 函数调用:
I have a Python function call like so:
import torchvision
model = torchvision.models.resnet18(pretrained=configs.use_trained_models)
哪个工作正常.
如果我试图让它变得动态:
If I attempt to make it dynamic:
import torchvision
model_name = 'resnet18'
model = torchvision.models[model_name](pretrained=configs.use_trained_models)
然后它失败了:
TypeError: 'module' object is not subscriptable
这是有道理的,因为 model
是一个导出一堆东西的模块,包括 resnet 函数:
Which makes sense since model
is a module which exports a bunch of things, including the resnet functions:
# __init__.py for the "models" module
...
from .resnet import *
...
如何在不提前知道函数名称的情况下动态调用这个函数(除了我得到一个带有函数名称的字符串)?
How can I call this function dynamically without knowing ahead of time its name (other than that I get a string with the function name)?
推荐答案
您可以使用 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.
这篇关于如何使用字符串按名称动态调用 Python 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文