在Python程序中给定带有函数名称的字符串调用函数的最佳方法是什么.例如,假设我有一个模块foo
,我有一个内容为的字符串"bar"
.什么是最好的打电话foo.bar()
?
我需要获取函数的返回值,这就是我不仅仅使用它的原因eval
.我想通过使用eval
定义一个返回该函数调用结果的临时函数来做到这一点,但我希望有更优雅的方法来做到这一点.
Pat*_*yer 1889
假设模块foo
有方法bar
:
import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()
Run Code Online (Sandbox Code Playgroud)
就此而言,第2行和第3行可以压缩为:
result = getattr(foo, 'bar')()
Run Code Online (Sandbox Code Playgroud)
如果这对你的用例更有意义.您可以getattr
以这种方式使用类实例绑定方法,模块级方法,类方法......列表继续.
sas*_*nin 501
locals()["myfunction"]()
Run Code Online (Sandbox Code Playgroud)
要么
globals()["myfunction"]()
Run Code Online (Sandbox Code Playgroud)
locals返回带有当前本地符号表的字典.globals返回带有全局符号表的字典.
HS.*_*HS. 309
帕特里克的解决方案可能是最干净的.如果您还需要动态选择模块,可以将其导入为:
module = __import__('foo')
func = getattr(module, 'bar')
func()
Run Code Online (Sandbox Code Playgroud)
小智 101
只是一个简单的贡献.如果我们需要实例的类在同一个文件中,我们可以使用这样的东西:
# 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()
Run Code Online (Sandbox Code Playgroud)
例如:
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')
Run Code Online (Sandbox Code Playgroud)
而且,如果不是一个类:
def sampleFunc(arg):
print('you called sampleFunc({})'.format(arg))
globals()['sampleFunc']('sample arg')
Run Code Online (Sandbox Code Playgroud)
fer*_*eel 90
给定一个字符串,具有函数的完整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()
Run Code Online (Sandbox Code Playgroud)
小智 48
根据Python编程常见问题解答的最佳答案是:
functions = {'myfoo': foo.bar}
mystring = 'myfoo'
if mystring in functions:
functions[mystring]()
Run Code Online (Sandbox Code Playgroud)
这种技术的主要优点是字符串不需要匹配函数的名称.这也是用于模拟案例构造的主要技术
005*_*005 38
答案(我希望)没有人想过
Eval喜欢的行为
getattr(locals().get("foo") or globals().get("foo"), "bar")()
Run Code Online (Sandbox Code Playgroud)
为什么不添加自动导入
getattr(
locals().get("foo") or
globals().get("foo") or
__import__("foo"),
"bar")()
Run Code Online (Sandbox Code Playgroud)
如果我们有额外的词典,我们想检查
getattr(next((x for x in (f("foo") for f in
[locals().get, globals().get,
self.__dict__.get, __import__])
if x)),
"bar")()
Run Code Online (Sandbox Code Playgroud)
我们需要更深入
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")()
Run Code Online (Sandbox Code Playgroud)
tru*_*one 24
对于它的价值,如果你需要将函数(或类)名称和应用程序名称作为字符串传递,那么你可以这样做:
myFnName = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn = getattr(app,myFnName)
Run Code Online (Sandbox Code Playgroud)
tvt*_*173 19
试试这个.虽然这仍然使用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)
Run Code Online (Sandbox Code Playgroud)
小智 17
在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]
Run Code Online (Sandbox Code Playgroud)
Nat*_*rip 15
没有任何建议对我有帮助.我确实发现了这一点.
<object>.__getattribute__(<string name>)(<params>)
Run Code Online (Sandbox Code Playgroud)
我正在使用python 2.66
希望这可以帮助
Ser*_*jik 12
作为这个问题如何使用方法名称分配给一个标记为重复的变量 [duplicate] 动态调用类中的方法,我在这里发布了一个相关的答案:
场景是,类中的一个方法想要动态调用同一个类上的另一个方法,我在原始示例中添加了一些细节,提供了一些更广泛的场景和清晰度:
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()
Run Code Online (Sandbox Code Playgroud)
输出(Python 3.7.x)
功能1:12
功能2:12
U10*_*ard 12
还没有人提到operator.attrgetter
:
>>> from operator import attrgetter
>>> l = [1, 2, 3]
>>> attrgetter('reverse')(l)()
>>> l
[3, 2, 1]
>>>
Run Code Online (Sandbox Code Playgroud)
尽管 getattr() 是优雅的(大约快 7 倍)方法,但您可以使用 eval 从函数(本地、类方法、模块)获取返回值,就像x = eval('foo.bar')()
. 当你实现一些错误处理时,就会非常安全(同样的原则可以用于 getattr)。模块导入和类的示例:
# import module, call module function, pass parameters and print retured value with eval():
import random
bar = 'random.randint'
randint = eval(bar)(0,100)
print(randint) # will print random int from <0;100)
# also class method returning (or not) value(s) can be used with eval:
class Say:
def say(something='nothing'):
return something
bar = 'Say.say'
print(eval(bar)('nice to meet you too')) # will print 'nice to meet you'
Run Code Online (Sandbox Code Playgroud)
当模块或类不存在(错别字或其他更好的东西)时,将引发 NameError。当函数不存在时,则引发 AttributeError。这可用于处理错误:
# try/except block can be used to catch both errors
try:
eval('Say.talk')() # raises AttributeError because function does not exist
eval('Says.say')() # raises NameError because the class does not exist
# or the same with getattr:
getattr(Say, 'talk')() # raises AttributeError
getattr(Says, 'say')() # raises NameError
except AttributeError:
# do domething or just...
print('Function does not exist')
except NameError:
# do domething or just...
print('Module does not exist')
Run Code Online (Sandbox Code Playgroud)
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."
Run Code Online (Sandbox Code Playgroud)