Python 使用模块的名称(字符串)调用模块的函数
在Python程序中,调用函数的最佳方法是使用函数名指定字符串。例如,假设我有一个模块Python 使用模块的名称(字符串)调用模块的函数,python,object,Python,Object,在Python程序中,调用函数的最佳方法是使用函数名指定字符串。例如,假设我有一个模块foo,我有一个字符串,其内容是“bar”。调用foo.bar()的最佳方法是什么 我需要获取函数的返回值,这就是为什么我不使用eval。通过使用eval定义一个返回函数调用结果的临时函数,我找到了实现这一点的方法,但我希望有一种更优雅的方法来实现这一点。假设模块foo带有方法bar: import foo method_to_call = getattr(foo, 'bar') result = method
foo
,我有一个字符串,其内容是“bar”
。调用foo.bar()
的最佳方法是什么
我需要获取函数的返回值,这就是为什么我不使用
eval
。通过使用eval
定义一个返回函数调用结果的临时函数,我找到了实现这一点的方法,但我希望有一种更优雅的方法来实现这一点。假设模块foo
带有方法bar
:
import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()
您可以将第2行和第3行缩短为:
result = getattr(foo, 'bar')()
如果这对您的用例更有意义的话
您可以以这种方式在类实例绑定方法、模块级方法、类方法。。。名单还在继续。帕特里克的解决方案可能是最干净的。 如果您还需要动态拾取模块,则可以按如下方式导入它:
module = __import__('foo')
func = getattr(module, 'bar')
func()
或
返回包含当前本地符号表的词典。返回带有全局符号表的字典。如果需要将函数(或类)名称和应用程序名称作为字符串传递,则可以执行以下操作:
myFnName = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn = getattr(app,myFnName)
只是一个简单的贡献。如果我们需要实例化的类在同一个文件中,我们可以使用如下内容:
# 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')
所建议的一切对我都没有帮助。但我确实发现了这一点
<object>.__getattribute__(<string name>)(<params>)
。\uuuu getattribute\uuuuu()()
我正在使用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()
答案(我希望)没有人想要
类评价行为
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")()
根据调查结果,最好的答案是:
functions = {'myfoo': foo.bar}
mystring = 'myfoo'
if mystring in functions:
functions[mystring]()
这种技术的主要优点是字符串不需要与函数名匹配。这也是用于模拟案例构造的主要技术
试试这个。虽然它仍然使用eval,但它只使用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)
由于这个问题与这个问题相同,我在这里发布了一个相关的答案:
场景是,一个类中的一个方法想要动态调用同一个类上的另一个方法,我在原始示例中添加了一些细节,提供了一些更广泛的场景和清晰性:
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
这是一个简单的答案,例如,这将允许您清除屏幕。下面有两个示例,分别是eval和exec,它们将在清理后在顶部打印0(如果您使用的是Windows,请将
clear
更改为cls
,Linux和Mac用户将按原样离开)或仅执行它
eval("os.system(\"clear\")")
exec("os.system(\"clear\")")
getattr
从对象按名称调用方法。
但是这个对象应该是调用类的父对象。
父类可以通过super(self.\uuuu class\uuuuu,self)
类库:
def调用库(func):
“这不起作用”
定义新函数(self、*args、**kwargs):
名称=函数名称__
getattr(super(self.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu类,self),name)(*args,**kwargs)
返回新函数
def f(自身,*参数):
打印(f“调用的基本方法”)
def g(自身,*参数):
打印(f“调用的基本方法”)
类继承(基):
@Base.call_Base
def f(自身,*参数):
“”“装饰程序将忽略函数体。”“”
通过
@Base.call_Base
def g(自身,*参数):
“”“装饰程序将忽略函数体。”“”
通过
Inherit().f()#目标是打印“已调用的基本方法”
尽管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'
我以前也遇到过类似的问题,那就是将字符串转换为函数但我不能使用
eval()
或ast.literal\u eval()
,因为我不想立即执行此代码。
e、 g.我有一个字符串“foo.bar”
,我想把它作为函数名而不是字符串分配给x
,这意味着我可以通过x()
按需调用函数
这是我的密码:
str\u to\u convert=“foo.bar”
exec(f“x={str_to_convert}”)
x()
至于您的问题,您只需在{}
之前添加模块名foo
和
,如下所示:
str\u to\u convert=“bar”
exec(f“x=foo.{str_to_convert}”)
x()
警告!!!无论是eval()
还是exec()
都是危险的方法,您应该确认安全性。
警告!!!无论是eval()
还是exec()
都是危险的方法,您应该确认安全性。
警告!!!无论是
eval()
还是exec()
都是一种危险的方法,您应该确认安全性。我不理解最后的评论__import_uu有自己的权利,在提到的文档中的下一句话是:“直接使用_uimport_uuu()是很少见的,除非您想导入一个只有在运行时才知道名称的模块”。因此,对于给定的答案:+1。使用importlib.import\u模块
。官员会
eval("os.system(\"clear\")")
exec("os.system(\"clear\")")
# 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'
# 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')