如果它是在一个类中,你可以使用GETATTR:
class MyClass(object):
def install(self):
print "In install"
method_name = 'install' # set by the command line options
my_cls = MyClass()
method = None
try:
method = getattr(my_cls, method_name)
except AttributeError:
raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))
()方法 或者如果它是一个功能:
def install():
print "In install"
method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
raise NotImplementedError("Method %s not implemented" % method_name)
method()
你的意思是你想*动态查找属性*?为此使用'getattr()'。 –
你的情况:'getattr(bar,foo).baz()'。 –
哦..有道理,谢谢。我不确定getattr()是这样工作的。谢谢。 (对不起,重复) –