python - 通过字符串调用方法

标签 python python-2.5

我有以下类(class)。

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

对于私有(private)函数:

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

关于python - 通过字符串调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11649848/

相关文章:

python - 为什么套接字行为依赖于打印语句?

python - 如何使用 Python 3 阅读电子邮件

python - 恢复 TensorFlow 模型

python - 我可以设置 IDLE 默认启动 Python 2.5 吗?

python - 使用 python os.path 模块分隔文件扩展名

python - 使用 scipy 对数据框中的组进行方差分析

python - 在列表中找到重新编译匹配项的最快方法

python - 在 Python 2.5 上使用 MySQLdb

python - 如何添加json库

python - 在 Python 中混合使用不常见的字符