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

import foo
func_name = "bar"
call(foo, func_name)  # calls foo.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')

其他回答

试试这个。虽然这仍然使用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)

给定一个字符串和一个函数的完整python路径,这就是我如何获得所述函数的结果:

import importlib
function_string = 'mypackage.mymodule.myfunc'
mod_name, func_name = function_string.rsplit('.',1)
mod = importlib.import_module(mod_name)
func = getattr(mod, func_name)
result = func()

关于这个问题,如何使用方法名分配给标记为与此重复的变量[重复]来动态调用类中的方法,我在这里发布了一个相关的答案:

场景是,一个类中的一个方法想要动态调用同一个类上的另一个方法,我在原始示例中添加了一些细节,这提供了更广泛的场景和清晰性:

class MyClass:
    def __init__(self, i):
        self.i = i

    def get(self):
        func = getattr(MyClass, 'function{}'.format(self.i))
        func(self, 12)   # This one will work
        # self.func(12)    # But this does NOT work.


    def function1(self, p1):
        print('function1: {}'.format(p1))
        # do other stuff

    def function2(self, p1):
        print('function2: {}'.format(p1))
        # do other stuff


if __name__ == "__main__":
    class1 = MyClass(1)
    class1.get()
    class2 = MyClass(2)
    class2.get()

输出(Python 3.7.x)功能1:12功能2:12

这些建议对我都没有帮助。但我确实发现了这一点。

<object>.__getattribute__(<string name>)(<params>)

我使用的是python 2.66

希望这有帮助

虽然getattr()是一种优雅的(大约快7倍)方法,但您可以使用eval从函数(local、class方法、模块)获得返回值,其优雅程度与x=eval('fo.bar')()相同。当您实现一些错误处理时,就会非常安全(getattr也可以使用相同的原理)。模块导入和类示例:

# import module, call module function, pass parameters and print retured value with eval():
import random
bar = 'random.randint'
randint = eval(bar)(0,100)
print(randint) # will print random int from <0;100)

# also class method returning (or not) value(s) can be used with eval: 
class Say:
    def say(something='nothing'):
        return something

bar = 'Say.say'
print(eval(bar)('nice to meet you too')) # will print 'nice to meet you' 

当模块或类不存在(键入错误或其他更好的错误)时,就会引发NameError。如果函数不存在,则引发AttributeError。这可用于处理错误:

# try/except block can be used to catch both errors
try:
    eval('Say.talk')() # raises AttributeError because function does not exist
    eval('Says.say')() # raises NameError because the class does not exist
    # or the same with getattr:
    getattr(Say, 'talk')() # raises AttributeError
    getattr(Says, 'say')() # raises NameError
except AttributeError:
    # do domething or just...
    print('Function does not exist')
except NameError:
    # do domething or just...
    print('Module does not exist')