如何在python中动态调用方法?

I w*_*ges 2 variables methods dynamic call python-2.7

我想用dinamically调用一个对象方法.

变量"MethodWanted"包含我想要执行的方法,变量"ObjectToApply"包含该对象.到目前为止我的代码是:

MethodWanted=".children()"

print eval(str(ObjectToApply)+MethodWanted)
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

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

我也试过没有str()包装对象,但后来我得到了"无法使用+与str和对象类型"错误.

当没有动态时,我可以这样做:

ObjectToApply.children()
Run Code Online (Sandbox Code Playgroud)

我得到了理想的结果.

怎么做dinamically?

Mar*_*ers 10

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

MethodWanted = 'children'

getattr(ObjectToApply, MethodWanted)()
Run Code Online (Sandbox Code Playgroud)

请注意,方法名称children不是.children().不要在这里混淆语法和名称.getattr()只返回方法对象,你仍然需要调用它(jusing ()).

  • @ManojAwasthi:那是因为 `sys.path` 不是一种方法。你也永远不会做“sys.path()”。 (2认同)