定义的类的具体方法我有此示例代码运行通过串
class aaa:
@staticmethod
def method(self):
pass
@staticmethod
def method2(self):
pass
command = 'method'
现在我想运行由命令串所定义的类AAA的方法。我怎么能这样做?非常感谢你。
定义的类的具体方法我有此示例代码运行通过串
class aaa:
@staticmethod
def method(self):
pass
@staticmethod
def method2(self):
pass
command = 'method'
现在我想运行由命令串所定义的类AAA的方法。我怎么能这样做?非常感谢你。
首先,删除staticmethod
s的self
参数 - staticmethod
s的整点是它们没有self
参数。然后,使用
method = getattr(aaa, command)
method()
或者干脆
getattr(aaa, command)()
调用由command
命名方法。
(我只是想知道你为什么不干脆在首位使用command = aaa.method
,但也有一定的应用场合,这是不可能的。)
可以使用getattr
通过名字得到一个对象的属性。
In [141]: class Foo(object):
.....: def frob(self):
.....: print "Frobbed"
.....:
.....:
In [142]: f = Foo()
In [143]: getattr(f, 'frob')
Out[143]: <bound method Foo.frob of <__main__.Foo object at 0x2374350>>
In [144]: _()
Frobbed
不要。这种方法引入的问题(安全性,清洁性,性能,可读性等)很少有理由处理。只需使用command = aaa.method
。
如果有使用字符串(希望一个很好的理由),你可以使用getattr
但你propably应该使用显式映射指定所有有效名称(这也使得对内部代码面向未来重命名/重构):
methods = {
'method': aaa.method,
'method2': aaa.method2,
}
methods[command]()
案例“该字符串没有方法”,可以这样处理:
method = methods.get(command)
if method is None:
... # handle error/bail out
静态方法不应该有一个'self' PA rameter。静态方法不与任何类或实例属性交互。 – Daenyth 2011-04-26 15:43:40