假设我有一个模块" foo",并且有一个字符串,其内容为" bar"。如何调用foo.bar()
解决方案
假设模块foo
和方法bar
:
import foo method_to_call = getattr(foo, 'bar') result = method_to_call()
到目前为止,第2行和第3行可以压缩为:
result = getattr(foo, 'bar')()
我们可以通过这种方式在类实例绑定的方法,模块级方法,类方法上使用getattr
列表继续。
如果我们还需要动态提取模块,则可以按以下方式导入它:
module = __import__('foo') func = getattr(module, 'bar') func()
日期:2020-03-24 13:44:38 来源:oir作者:oir