8

I would like to call an object method dynamically.

The variable "MethodWanted" contains the method I want to execute, the variable "ObjectToApply" contains the object. My code so far is:

MethodWanted=".children()"

print eval(str(ObjectToApply)+MethodWanted)

But I get the following error:

exception executing script
  File "<string>", line 1
    <pos 164243664 childIndex: 6 lvl: 5>.children()
    ^
SyntaxError: invalid syntax

I also tried without str() wrapping the object, but then I get a "cant use + with str and object types" error.

When not dynamically, I can just execute this code to get the desired result:

ObjectToApply.children()

How to do that dynamically?

4

1 回答 1

21

方法只是属性,因此用于getattr()动态检索一个:

MethodWanted = 'children'

getattr(ObjectToApply, MethodWanted)()

请注意,方法名称是children,而不是.children()。不要将语法与此处的名称混淆。getattr()只返回方法对象,你仍然需要调用它(jusing ())。

于 2013-07-18T14:23:52.537 回答