How to dynamically call a method in python?

谁说胖子不能爱 提交于 2021-02-05 06:10:07

问题


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?


回答1:


Methods are just attributes, so use getattr() to retrieve one dynamically:

MethodWanted = 'children'

getattr(ObjectToApply, MethodWanted)()

Note that the method name is children, not .children(). Don't confuse syntax with the name here. getattr() returns just the method object, you still need to call it (jusing ()).



来源:https://stackoverflow.com/questions/17726180/how-to-dynamically-call-a-method-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!