【发布时间】:2016-06-06 23:16:53
【问题描述】:
我想复制一个类,同时更新它的所有方法以引用一组新的__globals__
我在想类似下面的事情,但是与types.FunctionType 不同,types.UnboundMethodType 的构造函数不接受__globals__,有什么建议可以解决这个问题吗?
def copy_class(old_class, new_module):
"""Copies a class, updating __globals__ of all methods to point to new_module"""
new_dict = {}
for name, entry in old_class.__dict__.items():
if isinstance(entry, types.UnboundMethodType):
entry = types.UnboundMethodType(name, None, old_class.__class__, globals=new_module.__dict__)
new_dict[name] = entry
return type(old_class.name, old_class.__bases__, new_dict)
【问题讨论】:
标签: python python-2.7 monkeypatching