gpt4 book ai didi

variables - 如何动态调用python中的方法?

转载 作者:行者123 更新时间:2023-12-03 18:33:12 24 4
gpt4 key购买 nike

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

变量“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()动态检索一个:

MethodWanted = 'children'

getattr(ObjectToApply, MethodWanted)()

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

关于variables - 如何动态调用python中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17726180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com