【问题标题】:How to call Python function by name dynamically using a string?如何使用字符串按名称动态调用 Python 函数?
【发布时间】:2021-05-07 04:11:10
【问题描述】:

我有一个这样的 Python 函数调用:

import torchvision

model = torchvision.models.resnet18(pretrained=configs.use_trained_models)

效果很好。

如果我尝试使其动态化:

import torchvision

model_name = 'resnet18'
model = torchvision.models[model_name](pretrained=configs.use_trained_models)

然后它失败了:

TypeError: 'module' object is not subscriptable

这是有道理的,因为model 是一个导出一堆东西的模块,包括 resnet 函数:

# __init__.py for the "models" module

...
from .resnet import * 
...

如何在不提前知道函数名称的情况下动态调用这个函数(除了我得到一个带有函数名称的字符串)?

【问题讨论】:

    标签: python module python-3.8


    【解决方案1】:

    你可以使用getattr函数:

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

    这基本上与点表示法相同,只是在接受字符串以检索属性/方法的函数形式中。

    【讨论】:

    • 完美!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2020-11-15
    • 2011-12-17
    • 2023-03-24
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2013-07-18
    相关资源
    最近更新 更多