通过字符串调用方法

2023-11-27

我有以下课程。

func_list= ["function1", "function2", "function3"]

class doit(object):
    def __init__(self):
        for item in func_list:
            if item == "function1":
                self.function1()
            elif item == "function2":
                self.function2()
            elif item == "function3":
                self.function3()

    def function1(self):
        #do this
        pass
    def function2(self):
        #do that
        pass
    def function3(self):
        pass

如果创建了此类的实例,它将迭代字符串列表并根据实际字符串调用方法。列表中的字符串具有相应方法的名称。

我怎样才能以更优雅的方式做到这一点? 我不想添加另一个elif-我添加到列表中的每个“功能”的路径。


func_list= ["function1", "function2", "function3"]

class doit(object):
    def __init__(self):
        for item in func_list:
            getattr(self, item)()
    def function1(self):
        print "f1"
    def function2(self):
        print "f2"
    def function3(self):
        print "f3"



>>> doit()
f1
f2
f3

对于私有函数:

for item in func_list:
     if item.startswith('__'):
         getattr(self, '_' + self.__class__.__name__+ item)()
     else:
         getattr(self, item)()

.

getattr(object, name[, default])

返回对象的命名属性的值。名称必须是字符串。如果字符串是对象属性之一的名称,则结果是该属性的值。例如,getattr(x, 'foobar') 相当于 x.foobar。如果指定的属性不存在,则返回默认值(如果提供),否则引发 AttributeError。

http://docs.python.org/library/functions.html#getattr

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过字符串调用方法 的相关文章

随机推荐