如何使用带有函数名称的字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
给定具有方法 bar
的模块 foo
:
import foo
bar = getattr(foo, 'bar')
result = bar()
getattr
可以类似地用于类实例绑定方法、模块级方法、类方法……不胜枚举。
使用 locals(),它返回一个带有当前本地符号表的字典:locals()["myfunction"]()
使用 globals(),它返回一个带有全局符号表的字典: globals()["myfunction"]()
基于 Patrick's solution,要动态获取模块,请使用以下命令导入:
module = __import__('foo')
func = getattr(module, 'bar')
func()
importlib.import_module
。官方文档说 __import__
:“这是日常 Python 编程中不需要的高级函数,与 importlib.import_module() 不同。” docs.python.org/2/library/functions.html#__import__
importlib.import_module
。请参阅docs.python.org/3.6/library/…
只是一个简单的贡献。如果我们需要实例化的类在同一个文件中,我们可以使用如下内容:
# 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')
给定一个字符串,一个函数的完整 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()
__import__
函数的轻量级版本。
根据 Python programming FAQ 的最佳答案是:
functions = {'myfoo': foo.bar}
mystring = 'myfoo'
if mystring in functions:
functions[mystring]()
这种技术的主要优点是字符串不需要匹配函数的名称。这也是用于模拟案例构造的主要技术
答案(我希望)没人想要
评估类行为
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")()
对于它的价值,如果您需要将函数(或类)名称和应用程序名称作为字符串传递,那么您可以这样做:
myFnName = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn = getattr(app,myFnName)
handler = getattr(sys.modules[__name__], myFnName)
尝试这个。虽然这仍然使用 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
。 getattr(__module__, method_name)
在这种情况下是一个更好的选择。
由于此问题 How to dynamically call methods within a class using method-name assignment to a variable [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()
输出 (Python 3.7.x) 函数 1:12 函数 2:12
任何建议都没有帮助我。我确实发现了这一点。
<object>.__getattribute__(<string name>)(<params>)
我正在使用 python 2.66
希望这可以帮助
self.__getattribute__('title')
等于 self.title
self.__getattribute__('title')
在任何情况下都不起作用(不知道为什么),但 func = getattr(self, 'title'); func();
可以。所以,也许改用 getattr()
更好
getattr
。
尽管 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'
当模块或类不存在(错字或更好的东西)时,会引发 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')
在 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]
getattr(obj, attr)
代替。
还没有人提到 operator.attrgetter
:
>>> from operator import attrgetter
>>> l = [1, 2, 3]
>>> attrgetter('reverse')(l)()
>>> l
[3, 2, 1]
>>>
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
,这意味着我可以通过 x()
ON DEMAND 调用该函数。
这是我的代码:
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()
都是危险的方法,您应该确认安全性。
eval()
代替 exec()
,并且可能会使代码更具可读性:只需使用 x = eval(str_to_convert)
代替即可获得相同的结果。
你的意思是从模块中获取指向内部函数的指针
import foo
method = foo.bar
executed = method(parameter)
对于准时的情况,这不是更好的pythonic方式确实是可能的
"bar"
存储为字符串时,您不能使用此方法...
这是一个简单的答案,例如,这将允许您清除屏幕。下面有两个示例,使用 eval 和 exec,清理后将在顶部打印 0(如果您使用的是 Windows,请将 clear
更改为 cls
,例如 Linux 和 Mac 用户保持原样)或执行它,分别。
eval("os.system(\"clear\")")
exec("os.system(\"clear\")")
不定期副业成功案例分享
foo
模块中,您可以使用globals()
来执行此操作:methodToCall = globals()['bar']