Variables 如何在python中动态调用方法?
我想动态调用一个对象方法 变量“MethodWanted”包含我要执行的方法,变量“ObjectToApply”包含对象。 到目前为止,我的代码是:Variables 如何在python中动态调用方法?,variables,dynamic,python-2.7,methods,call,Variables,Dynamic,Python 2.7,Methods,Call,我想动态调用一个对象方法 变量“MethodWanted”包含我要执行的方法,变量“ObjectToApply”包含对象。 到目前为止,我的代码是: MethodWanted=".children()" print eval(str(ObjectToApply)+MethodWanted) 但我得到了以下错误: exception executing script File "<string>", line 1 <pos 164243664 childIndex
MethodWanted=".children()"
print eval(str(ObjectToApply)+MethodWanted)
但我得到了以下错误:
exception executing script
File "<string>", line 1
<pos 164243664 childIndex: 6 lvl: 5>.children()
^
SyntaxError: invalid syntax
如何动态地执行此操作?方法只是属性,因此使用
getattr()
动态地检索一个:
MethodWanted = 'children'
getattr(ObjectToApply, MethodWanted)()
请注意,方法名称是
children
,而不是.children()
。不要将语法与此处的名称混淆getattr()
只返回方法对象,您仍然需要调用它(jusing()
)。刚刚尝试了getattr(sysobj,'path')
其中sysobj
是一个sys
对象。它在不带()的情况下工作。@ManojAwasthi:这是因为sys.path
不是一个方法。你也永远不会做sys.path()
。哇,非常感谢。我错过了()的最后(无法想象它会是那样)工作完美!
MethodWanted = 'children'
getattr(ObjectToApply, MethodWanted)()