按名称调用 Python 方法 [英] Call a Python method by name

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

问题描述

如果我在字符串中有一个对象和一个方法名称,我该如何调用该方法?

If I have an object and a method name in a string, how can I call the method?

class Foo:
    def bar1(self):
        print 1
    def bar2(self):
        print 2

def callMethod(o, name):
    ???

f = Foo()
callMethod(f, "bar1")

推荐答案

使用内置的 getattr() 函数:

Use the built-in getattr() function:

class Foo:
    def bar1(self):
        print(1)
    def bar2(self):
        print(2)

def call_method(o, name):
    return getattr(o, name)()


f = Foo()
call_method(f, "bar1")  # prints 1

您也可以使用 setattr()用于按名称设置类属性.

You can also use setattr() for setting class attributes by names.

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

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