如何使用带有函数名称的字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
如何使用带有函数名称的字符串调用函数?例如:
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样行为
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")()
试试这个。虽然这仍然使用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)
这是一个简单的答案,例如,这将允许您清除屏幕。下面有两个示例,分别是eval和exec,它们将在清理后在顶部打印0(如果您使用的是Windows,请将clear更改为cls,例如,Linux和Mac用户保持原样)或仅执行它。
eval("os.system(\"clear\")")
exec("os.system(\"clear\")")
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."
在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]