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

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

当前回答

你的意思是从模块中获取指向内部函数的指针

import foo
method = foo.bar
executed = method(parameter)

这并不是一种更好的蟒蛇方式,对于准时的情况确实是可能的

其他回答

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

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

我以前也遇到过类似的问题,那就是将字符串转换为函数。但我不能使用eval()或ast.literal_eval(),因为我不想立即执行这段代码。

例如,我有一个字符串“foo.bar”,我想将它指定给x作为函数名,而不是字符串,这意味着我可以在DEMAND上通过x()调用函数。

这是我的代码:

str_to_convert = "foo.bar"
exec(f"x = {str_to_convert}")
x()

至于您的问题,您只需要添加模块名foo和。在{}之前,如下所示:

str_to_convert = "bar"
exec(f"x = foo.{str_to_convert}")
x()

警告!!!eval()或exec()是一种危险的方法,您应该确认其安全性。警告!!!eval()或exec()是一种危险的方法,您应该确认其安全性。警告!!!eval()或exec()是一种危险的方法,您应该确认其安全性。

在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]

你的意思是从模块中获取指向内部函数的指针

import foo
method = foo.bar
executed = method(parameter)

这并不是一种更好的蟒蛇方式,对于准时的情况确实是可能的