[英]python class __dict__ usage for cloning object attributes
EDIT Clarification: While I do appreciate the corrections/suggestions for deep copy
that are already posted, this question is mainly about usage of __dict__
method of class, and whether cloning object attrs using init this way is okay. 编辑澄清:虽然我确实感谢已经发布的针对深层
copy
的更正/建议,但这个问题主要是关于__dict__
类的用法,以及使用init以此方式克隆对象属性是否可行。
Is there any issue with this usage of init for copying object attrs, better way to achieve this? 使用init复制对象attrs是否有任何问题,这是实现此目标的更好方法?
class CopyClass(obj):
def __init__(self, obj1):
super().__init__()
self.__dict__ = obj1.__dict__.copy()
obj2 = CopyClass(obj1)
You can simply use copy.deepcopy()
. 您可以简单地使用
copy.deepcopy()
。
from copy import deepcopy
obj = Foo() # Foo is some random class
obj_copy = deepcopy(obj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.