如何在python中动态调用方法? [英] How to dynamically call a method in python?

查看:96
本文介绍了如何在python中动态调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态地调用对象方法.

I would like to call an object method dynamically.

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

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)

但是出现以下错误:

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

我也尝试了不使用str()包装对象,但随后出现无法使用+带有str和对象类型的错误".

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?

推荐答案

方法只是属性,因此请使用 getattr()动态地获取一个方法:

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

MethodWanted = 'children'

getattr(ObjectToApply, MethodWanted)()

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

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 ()).

这篇关于如何在python中动态调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆