如何使用带有函数名称的字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
如何使用带有函数名称的字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
当前回答
你的意思是从模块中获取指向内部函数的指针
import foo
method = foo.bar
executed = method(parameter)
这并不是一种更好的蟒蛇方式,对于准时的情况确实是可能的
其他回答
只是一个简单的贡献。如果我们需要实例化的类在同一个文件中,我们可以使用类似的方法:
# 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')
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."
值得一提的是,如果您需要将函数(或类)名称和应用程序名称作为字符串传递,那么可以这样做:
myFnName = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn = getattr(app,myFnName)
这些建议对我都没有帮助。但我确实发现了这一点。
<object>.__getattribute__(<string name>)(<params>)
我使用的是python 2.66
希望这有帮助
给定一个字符串和一个函数的完整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()