Python 通过字符串调用方法

Python 通过字符串调用方法,python,python-2.5,Python,Python 2.5,我有以下课程 func_list= ["function1", "function2", "function3"] class doit(object): def __init__(self): for item in func_list: if item == "function1": self.function1() elif item == "function2":

我有以下课程

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(x,'foobar')等同于x.foobar。如果命名属性不存在,则返回默认值(如果提供),否则将引发AttributeError


这通常通过字典查找来解决,因为函数是Python中的一流数据类型。例如:

# map string names to callable functions
dispatch = {'func1': func1, 'func2': func2, ...}

want_to_call = 'func1'
dispatch[want_to_call](args)

您可以使用eval,这使您的程序更加简单和简短

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

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

你为什么不用lambdas

比如说,

def func1(a):
    return a ** 2

def func2(a, b):
    return a ** 3 + b

dic = {'Hello':lambda x: func1(x), 'World':lambda x,y: func2(x, y)} #Map functions to lambdas
print dic['Hello'](3)
print dic['World'](2,3)
产出,9 11

或者,你可以这样做

class funs():
    def func1(self, a):
        return a ** 2

    def func2(self, a, b):
        return a ** 3 + b

f = funs()
dic = {'Hello': lambda x: f.func1(x), 'World': lambda x,y: f.func2(x,y)}
print dic['Hello'](3)
print dic['World'](5,4)

请注意,不要调用变量列表,因为它是python内置函数的名称。类似于
funclist
flist
的东西就可以了;)你应该把函数对象放在列表中,而不是STR,然后只调用每一个。我认为如果你提到魔法是在
getattr
函数中完成的,并提供一个到文档的链接,这个答案会稍微好一点。最好去掉列表变量,因为它没有被使用。@black\u dragon:Great,这就是我想做的。但是我如何访问
private
——像
def\uuu function4(self)这样的方法:打印“private”
?私有函数
\uu function4
将作为
\uu function4
访问,因为这就是名称如何被破坏而看起来是私有的。@wewa您应该避免
\uu name
。有关详细信息,请参阅。只需使用
\u name
。使用
exec
将是另一种可能性。-1、eval和exec是Python代码中永远不应该出现的东西。它们是安全漏洞,在这里完全是杀伤力过大。
def func1(a):
    return a ** 2

def func2(a, b):
    return a ** 3 + b

dic = {'Hello':lambda x: func1(x), 'World':lambda x,y: func2(x, y)} #Map functions to lambdas
print dic['Hello'](3)
print dic['World'](2,3)
class funs():
    def func1(self, a):
        return a ** 2

    def func2(self, a, b):
        return a ** 3 + b

f = funs()
dic = {'Hello': lambda x: f.func1(x), 'World': lambda x,y: f.func2(x,y)}
print dic['Hello'](3)
print dic['World'](5,4)