繁体   English   中英

使用模块名称(字符串)调用模块的 function

[英]Calling a function of a module by using its name (a string)

如何使用带有函数名称的字符串调用 function? 例如:

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 的解决方案,要动态获取模块,请使用以下命令导入:

module = __import__('foo')
func = getattr(module, 'bar')
func()

只是一个简单的贡献。 如果我们需要实例化的类在同一个文件中,我们可以使用如下内容:

# 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()

根据Python 编程常见问题解答的最佳答案是:

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)

尝试这个。 虽然这仍然使用 eval,但它只使用它从当前 context 中调用函数 然后,您就可以根据需要使用真正的功能了。

这样做对我的主要好处是,在调用函数时,您将收到任何与 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

任何建议都没有帮助我。 我确实发现了这一点。

<object>.__getattribute__(<string name>)(<params>)

我正在使用 python 2.66

希望这可以帮助

尽管 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]

还没有人提到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()都是危险的方法,您应该确认安全性。

在很多很多用例中,答案是“不要!”

而是执行以下操作:

safe_functions = {'baz':foo.baz, 'bar':foo.bar}
safe_functions['bar']()
safe_functions['delete_all_the_things']() 

你的意思是从模块中获取指向内部函数的指针

import foo
method = foo.bar
executed = method(parameter)

对于准时的情况,这不是更好的pythonic方式确实是可能的

这是一个简单的答案,例如,这将允许您清除屏幕。 下面有两个示例,使用 eval 和 exec,在清理后将在顶部打印 0(如果您使用的是 Windows,请将clear更改为cls ,例如 Linux 和 Mac 用户保持原样)或分别执行它。

eval("os.system(\"clear\")")
exec("os.system(\"clear\")")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM