我想动态地调用对象方法。
变量“ MethodWanted”包含我要执行的方法,变量“ ObjectToApply”包含对象。到目前为止,我的代码是:
MethodWanted=".children()"
print eval(str(ObjectToApply)+MethodWanted)
但我收到以下错误:
exception executing script
File "<string>", line 1
<pos 164243664 childIndex: 6 lvl: 5>.children()
^
SyntaxError: invalid syntax
我也尝试了不使用str()包装对象,但是随后出现“无法使用+带有str和对象类型”的错误。
如果不是动态的,我可以执行以下代码以获得所需的结果:
ObjectToApply.children()
如何动态地做到这一点?
方法只是属性,因此可用于getattr()
动态检索一个方法:
MethodWanted = 'children'
getattr(ObjectToApply, MethodWanted)()
请注意,方法名称children
不是.children()
。不要在这里将语法与名称混淆。getattr()
仅返回方法对象,您仍然需要调用它(jusing ()
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句