通过名称调用Python方法
如果我有一个对象和一个方法名是以字符串形式存在的,我该怎么调用这个方法呢?
class Foo:
def bar1(self):
print 1
def bar2(self):
print 2
def callMethod(o, name):
???
f = Foo()
callMethod(f, "bar1")
5 个回答
3
getattr(globals()['Foo'](), 'bar1')()
getattr(globals()['Foo'](), 'bar2')()
不需要先创建 Foo 的实例!
11
我之前也有类似的问题,想通过引用来调用实例方法。这里有一些有趣的发现:
instance_of_foo=Foo()
method_ref=getattr(Foo, 'bar')
method_ref(instance_of_foo) # instance_of_foo becomes self
instance_method_ref=getattr(instance_of_foo, 'bar')
instance_method_ref() # instance_of_foo already bound into reference
Python真是太棒了!