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

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

当前回答

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

其他回答

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

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

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")()

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

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

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

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."

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

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