如何使用带有函数名称的字符串调用函数?例如:

import foo
func_name = "bar"
call(foo, func_name)  # calls foo.bar()

当前回答

还没有人提到operator.attrgetter:

>>> from operator import attrgetter
>>> l = [1, 2, 3]
>>> attrgetter('reverse')(l)()
>>> l
[3, 2, 1]
>>> 

其他回答

在python3中,可以使用__getattribute__方法。请参见以下列表方法名称字符串示例:

func_name = 'reverse'

l = [1, 2, 3, 4]
print(l)
>> [1, 2, 3, 4]

l.__getattribute__(func_name)()
print(l)
>> [4, 3, 2, 1]

给定带有方法栏的模块foo:

import foo
bar = getattr(foo, 'bar')
result = bar()

getattr可以类似地用于类实例绑定方法、模块级方法、类方法。。。名单还在继续。

试试这个。虽然这仍然使用eval,但它只使用它从当前上下文调用函数。然后,您就可以随心所欲地使用真正的函数了。

这对我的主要好处是,在调用函数时,您将得到任何与eval相关的错误。然后,当您调用时,只会得到与函数相关的错误。

def say_hello(name):
    print 'Hello {}!'.format(name)

# get the function by name
method_name = 'say_hello'
method = eval(method_name)

# call it like a regular function later
args = ['friend']
kwargs = {}
method(*args, **kwargs)

答案(我希望)从来没有人想要

Eval样行为

getattr(locals().get("foo") or globals().get("foo"), "bar")()

为什么不添加自动导入

getattr(
    locals().get("foo") or 
    globals().get("foo") or
    __import__("foo"), 
"bar")()

万一我们有多余的字典要查

getattr(next((x for x in (f("foo") for f in 
                          [locals().get, globals().get, 
                           self.__dict__.get, __import__]) 
              if x)),
"bar")()

我们需要更深入

getattr(next((x for x in (f("foo") for f in 
              ([locals().get, globals().get, self.__dict__.get] +
               [d.get for d in (list(dd.values()) for dd in 
                                [locals(),globals(),self.__dict__]
                                if isinstance(dd,dict))
                if isinstance(d,dict)] + 
               [__import__])) 
        if x)),
"bar")()

只是一个简单的贡献。如果我们需要实例化的类在同一个文件中,我们可以使用类似的方法:

# Get class from globals and create an instance
m = globals()['our_class']()

# Get the function (from the instance) that we need to call
func = getattr(m, 'function_name')

# Call it
func()

例如:

class A:
    def __init__(self):
        pass

    def sampleFunc(self, arg):
        print('you called sampleFunc({})'.format(arg))

m = globals()['A']()
func = getattr(m, 'sampleFunc')
func('sample arg')

# Sample, all on one line
getattr(globals()['A'](), 'sampleFunc')('sample arg')

如果不是类:

def sampleFunc(arg):
    print('you called sampleFunc({})'.format(arg))

globals()['sampleFunc']('sample arg')