我想动态调用一个对象方法
变量“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()
动态检索一个:请注意,方法名称是
children
,而不是.children()
。不要将语法与此处的名称混淆getattr()
只返回方法对象,您仍然需要调用它(jusing()
)相关问题 更多 >
编程相关推荐