如果它是在一個類中,你可以使用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()是這樣工作的。謝謝。 (對不起,重複) –