Assuming module foo
with method bar
:
import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()
You could shorten lines 2 and 3 to:
result = getattr(foo, 'bar')()
if that makes more sense for your use case.
You can use getattr
in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…