【问题标题】:How to dynamically call a method in python?如何在python中动态调用方法?
【发布时间】:2013-07-17 13:32:06
【问题描述】:

我想动态调用一个对象方法。

变量“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()

如何动态地做到这一点?

【问题讨论】:

    标签: variables dynamic python-2.7 methods call


    【解决方案1】:

    方法只是属性,所以使用getattr()动态检索一个:

    MethodWanted = 'children'
    
    getattr(ObjectToApply, MethodWanted)()
    

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

    【讨论】:

    • 刚刚尝试过getattr(sysobj,'path'),其中sysobjsys 对象。它在没有 () 的情况下实际工作。
    • @ManojAwasthi:那是因为sys.path 不是一种方法。你也不会做sys.path()
    • 哇,非常感谢。最后我错过了 () (无法想象会是那样)完美地工作!
    猜你喜欢
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    相关资源
    最近更新 更多