Python从多模块导入方法动态定义类时方法绑定错误如何解决
问题根源
你的代码异常是Python闭包迟绑定特性导致的:
循环内定义的print_wrapper函数不会在定义时立刻捕获当前module变量的值,只有当方法被实际调用时才会查找该变量,此时循环已经执行结束,module固定指向最后加载的moduleB,因此所有实例的调用都指向了moduleB的方法,和方法能否拷贝无关。
解决方案
不需要修改原有模块,也不需要拷贝方法,只要在定义包装函数时绑定当前循环的module值即可,最简单的实现是用默认参数完成绑定(默认参数会在函数定义阶段完成求值,会保存当前循环的module实例):
修改后的核心代码
import os import re from importlib import import_module cwd = os.getcwd() for fileName in os.listdir(cwd): if re.search(r'module.+\.py', fileName): moduleName = re.split(r'\.', fileName)[0] module = import_module(moduleName) # 通过默认参数绑定当前循环的module值 def print_wrapper(self, text, module=module): module.print_something(text.upper()) className = f'ClassM{moduleName[1:]}' dynamicClass = type(className, (object, ), { "print_something": print_wrapper}) globals()[dynamicClass.__name__] = dynamicClass
运行验证
修改后执行测试代码:
instanceA = ClassModuleA() instanceA.print_something("testA") instanceB = ClassModuleB() instanceB.print_something("testB")
输出符合预期:
Here is some output from module A: TESTA
Here is some output from module B: TESTB
替代实现方案
也可以用functools.partial完成参数绑定,效果完全一致:
from functools import partial def print_wrapper(self, text, module): module.print_something(text.upper()) # 循环内绑定当前module dynamicClass = type(className, (object, ), { "print_something": partial(print_wrapper, module=module)})
内容的提问来源于stack exchange,提问作者umfundi
相关产品推荐
相关产品推荐

