Skip to main content
 首页 » 编程设计

python之如何与 getattr() 结合使用 lambda : in python 动态加载 python 模块

2025年05月04日13www_RR

环境(它是一个名为 nuke 的图形程序)提供了一个全局对象,我可以在其中添加菜单项并将其与函数连接。这个全局对象是这样工作的:

menu.addCommand("Do This!", lambda: DoThings()) 

我想动态读取 python 模块并将模块函数作为项目添加到全局菜单对象中。我写了一个类来做到这一点。我的类(class)的简化版本:

class mymenu(): 
. 
. 
. 
def _builMenuFromPath(self, basepath, module): 
 
    items = [] 
 
    # ... 
    # there is code to build the items list. this is a list of the python filenames 
    # ... 
 
    if len(items) > 0: 
 
        for item in items: 
 
            try: 
                f = getattr(__import__(module + "." + item), item) # item is the python filename of an module in the folder with the python files and module is the folder 
 
                menu.addCommand(item, lambda: f.call()) # f.call() is a function in the dynamic loaded python file 
 
            except Exception, e: 
                pass 

动态导入效果很好。但是每个生成的菜单项都链接到最后导入的函数。这样每个菜单项都做同样的事情。

我不是专业程序员。所以我认为我犯了一个简单的错误。

感谢您的帮助。

请您参考如下方法:

尝试传递 f.call 而不是 lambda:f.call()。