使用模块名称(字符串)调用模块函数

2024-11-18 08:41:00
admin
原创
142
摘要:问题描述:如何使用带有函数名称的字符串来调用函数?例如:import foo func_name = "bar" call(foo, func_name) # calls foo.bar() 解决方案 1:foo给定一个具有方法的模块bar:import foo bar = getatt...

问题描述:

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

import foo
func_name = "bar"
call(foo, func_name)  # calls foo.bar()

解决方案 1:

foo给定一个具有方法的模块bar

import foo
bar = getattr(foo, 'bar')
result = bar()

getattr可以类似地用于类实例绑定方法、模块级方法、类方法......等等。

解决方案 2:

  • 使用locals(),返回包含当前本地符号表的字典:

locals()["myfunction"]()
  • 使用globals(),返回包含全局符号表的字典:

globals()["myfunction"]()

解决方案 3:

根据Patrick 的解决方案,为了动态获取模块,请使用以下命令导入它:

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

解决方案 4:

只是一个简单的贡献。如果我们需要实例化的类在同一个文件中,我们可以使用类似这样的方法:

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

解决方案 5:

给定一个字符串,其中包含一个函数的完整 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()

解决方案 6:

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

functions = {'myfoo': foo.bar}

mystring = 'myfoo'
if mystring in functions:
    functions[mystring]()

这种技术的主要优点是字符串不需要与函数名称匹配。这也是用于模拟 case 构造的主要技术

解决方案 7:

我希望没有人想知道答案

类似 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")()

解决方案 8:

试试这个。虽然这仍然使用 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)

解决方案 9:

不管怎样,如果您需要将函数(或类)名称和应用程序名称作为字符串传递,那么您可以这样做:

myFnName  = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn  = getattr(app,myFnName)

解决方案 10:

由于这个问题如何使用方法名称分配给变量[重复]动态调用类中的方法标记为与此重复,我在这里发布了相关的答案:

场景是,类中的一个方法想要动态调用同一个类中的另一个方法,我在原始示例中添加了一些细节,以提供更广泛的场景和清晰度:

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

解决方案 11:

所有建议都对我没有帮助。不过我确实发现了这一点。

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

我正在使用 Python 2.66

希望这有帮助

解决方案 12:

尽管 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')

解决方案 13:

在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]

解决方案 14:

还没有人提到operator.attrgetter

>>> from operator import attrgetter
>>> l = [1, 2, 3]
>>> attrgetter('reverse')(l)()
>>> l
[3, 2, 1]
>>> 

解决方案 15:

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."

解决方案 16:

我以前遇到过类似的问题,即将字符串转换为函数。但我不能使用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()都是危险的方法,请确认其安全性。

解决方案 17:

已验证并测试:

# demo.py

import sys

def f1():
    print("Function 1 called")

def f2():
    print("Function 2 called")

def f3():
    print("Function 3 called")

def f4():
    print("Function 4 called")

functions = {
    "f1": __name__,
    "f2": __name__,
    "f3": __name__,
    "f4": __name__
}

function_name = input("Enter the name of the function you want to call: ")

try:
    func = getattr(sys.modules[functions[function_name]], function_name)
except Exception as e:
    print(f"Error: {e}")
else:
    func()

测试:

% python3 demo.py
Enter the name of the function you want to call: f1
Function 1 called

解决方案 18:

您应该看看qcall:

from qcall import call

call("foo.bar") # calls foo.bar()

解决方案 19:

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

eval("os.system(\"clear\")")
exec("os.system(\"clear\")")
相关推荐
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1267  
  IPD(Integrated Product Development)即集成产品开发,是一套先进的、成熟的产品开发管理理念、模式和方法。随着市场竞争的日益激烈,企业对于提升产品开发效率、降低成本、提高产品质量的需求愈发迫切,IPD 项目管理咨询市场也迎来了广阔的发展空间。深入探讨 IPD 项目管理咨询的市场需求与发展,...
IPD集成产品开发流程   27  
  IPD(Integrated Product Development)产品开发流程是一套先进的、被广泛应用的产品开发管理体系,它涵盖了从产品概念产生到产品推向市场并持续优化的全过程。通过将市场、研发、生产、销售等多个环节紧密整合,IPD旨在提高产品开发的效率、质量,降低成本,增强企业的市场竞争力。深入了解IPD产品开发...
IPD流程中TR   31  
  IPD(Integrated Product Development)测试流程是确保产品质量、提升研发效率的关键环节。它贯穿于产品从概念到上市的整个生命周期,对企业的成功至关重要。深入理解IPD测试流程的核心要点,有助于企业优化研发过程,打造更具竞争力的产品。以下将详细阐述IPD测试流程的三大核心要点。测试策略规划测试...
华为IPD   26  
  华为作为全球知名的科技企业,其成功背后的管理体系备受关注。IPD(集成产品开发)流程作为华为核心的产品开发管理模式,在创新管理与技术突破方面发挥了至关重要的作用。深入剖析华为 IPD 流程中的创新管理与技术突破,对于众多企业探索自身发展路径具有重要的借鉴意义。IPD 流程概述IPD 流程是一种先进的产品开发管理理念和方...
TR评审   26  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用