作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想制作类的副本,同时更新其所有方法以引用一组新的 __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)
最佳答案
__dict__
值是函数,而不是未绑定(bind)的方法。未绑定(bind)的方法对象仅在属性访问时创建。如果您在__dict__
中看到未绑定(bind)的方法对象,则说明在此函数到达之前您的类对象发生了一些奇怪的事情。
关于python - 如何对Python类进行深拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37668233/
我是一名优秀的程序员,十分优秀!