我有一组模块,我希望能够根据给定函数的参数在函数中调用其中一个。我试过这个,但它不起作用:
from my.set import modules
def get_modules(sub_mod):
variable = sub_mod
mod_object = modules.variable
function(mod_object)
我得到:
AttributeError: 'module' object has no attribute 'variable'
它没有接受我给它的参数,它是存在于 my.set.modules 下的模块的名称。因此,如果我调用函数 get_modules(name_of_mod_under_modules),我希望 modules.variable 行是“modules.name_of_mod_under_modules”,然后我可以将其作为对象传递给 mod_object。
最佳答案
在您当前的代码中,您正在寻找不存在的 modules.variable
,因此出现错误!这不是您获取对象属性的方式。
要实现您想要的效果,请使用 getattr
函数。
mod_object = getattr(modules, variable)
关于python - 如何在python函数中将变量分配给模块名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19918110/