如果我在字符串中有对象和方法名称,我该如何调用该方法?
class Foo:
def bar1(self):
print 1
def bar2(self):
print 2
def callMethod(o, name):
???
f = Foo()
callMethod(f, "bar1")
答案 0 :(得分:91)
简单的一个:
class Foo:
def bar1(self):
print 1
def bar2(self):
print 2
def callMethod(o, name):
getattr(o, name)()
f = Foo()
callMethod(f, "bar1")
查看getattr
您还可以使用setattr按名称设置Class属性。
答案 1 :(得分:5)
我有类似的问题,想通过引用调用实例方法。这是我发现的有趣的事情:
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太神奇了!
答案 2 :(得分:2)
getattr(globals()['Foo'](), 'bar1')()
getattr(globals()['Foo'](), 'bar2')()
无需首先实例化Foo!
答案 3 :(得分:1)
def callmethod(cls, mtd_name):
method = getattr(cls, mtd_name)
method()
答案 4 :(得分:0)
这是一个使用Python装饰器的更通用的版本。你可以用短名或长名打电话。我发现在使用short和long子命令实现CLI时很有用。
Python装饰器很精彩。 Bruce Eckel(Thinking in Java)在这里精美地描述了Python装饰器。
http://www.artima.com/weblogs/viewpost.jsp?thread=240808 http://www.artima.com/weblogs/viewpost.jsp?thread=240845
enum CellValue {
Undefined, One, Two, Three, Four, Five, Six, Seven, Eight, Nine;
public static CellValue fromInteger(int x) {
switch (x) {
case 0:
return Undefined;
case 1:
return One;
case 2:
return Two;
case 3:
return Three;
case 4:
return Four;
case 5:
return Five;
case 6:
return Six;
case 7:
return Seven;
case 8:
return Eight;
case 9:
return Nine;
}
return null;
}
public static int toInteger(CellValue value) throws Exception {
switch (value) {
case Undefined:
throw new Exception("Undefined cell value");
case One:
return 1;
case Two:
return 2;
case Three:
return 3;
case Four:
return 4;
case Five:
return 5;
case Six:
return 6;
case Seven:
return 7;
case Eight:
return 8;
case Nine:
return 9;
}
throw new Exception("Undefined Cell Value");
}
}