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

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

当前回答

使用locals(),它返回带有当前本地符号表的字典:locals()[“myfunction”]()使用globals(),它返回带有全局符号表的字典:globals()[“myfunction”]()

其他回答

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

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

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

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

# 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')

基于Patrick的解决方案,要动态获取模块,请使用以下方法导入:

module = __import__('foo')
func = getattr(module, 'bar')
func()

getattr根据对象的名称调用方法。但此对象应该是调用类的父对象。父类可以由super(self.__class__,self)获取

class Base:
    def call_base(func):
        """This does not work"""
        def new_func(self, *args, **kwargs):
            name = func.__name__
            getattr(super(self.__class__, self), name)(*args, **kwargs)
        return new_func

    def f(self, *args):
        print(f"BASE method invoked.")

    def g(self, *args):
        print(f"BASE method invoked.")

class Inherit(Base):
    @Base.call_base
    def f(self, *args):
        """function body will be ignored by the decorator."""
        pass

    @Base.call_base
    def g(self, *args):
        """function body will be ignored by the decorator."""
        pass

Inherit().f() # The goal is to print "BASE method invoked."

使用locals(),它返回带有当前本地符号表的字典:locals()[“myfunction”]()使用globals(),它返回带有全局符号表的字典:globals()[“myfunction”]()