从字符串调用方法 [英] Call method from string

查看:42
本文介绍了从字符串调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个Python类,并且想根据变量从中调用函数,我该怎么做?我想以下可以做到这一点:

If I have a Python class, and would like to call a function from it depending on a variable, how would I do so? I imagined following could do it:

class CallMe: # Class

   def App(): # Method one

      ...

   def Foo(): # Method two

      ...

variable = "App" # Method to call

CallMe.variable() # Calling App()

但是不能.还有其他方法吗?

But it couldn't. Any other way to do this?

推荐答案

您可以执行以下操作:

getattr(CallMe, variable)()

getattr 是一种内置方法,它返回命名属性的值对象.在这种情况下,该值是可以使用()调用的方法对象

getattr is a builtin method, it returns the value of the named attributed of object. The value in this case is a method object that you can call with ()

这篇关于从字符串调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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