本文介绍了使用deepcopy与字典里面的对象的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读文档,我明白 copy.deepcopy(obj)递归地复制这一个内的任何其他对象,但是当我运行时:

Reading the documentation, I understood that copy.deepcopy(obj) copies recursively any other object inside this one, but when I run:

>>> import copy
>>> class SomeObject:
...     a=1
...     b={1:1,2:2}
... 
>>> o1=SomeObject()
>>> o2=copy.deepcopy(o1)
>>> id(o1)
140041523635624
>>> id(o2)
140041523635912
>>> id(o1.b)
30087968
>>> id(o2.b)
30087968

似乎没有复制字典里面'O1'。任何人都可以告诉我,如果我做错了什么,或者如何获取对象内的字典副本?

It does not seem to be copying the dictionary inside 'o1'. Can anyone tell me if I am doing something wrong, or how can I get a copy of the dictionary inside the object?

谢谢

推荐答案

深层拷贝仅复制实例属性。您的 b 属性是一个类属性。

Deepcopy only copies instance attributes. Your b attribute is a class attribute, instead.

即使您没有 创建一个副本,但是一个新的实例 SomeObject 手动, b 仍然会被共享:

Even if you did not create a copy but a new instance of SomeObject manually, b would still be shared:

>>> class SomeObject:
...     a=1
...     b={1:1,2:2}
... 
>>> so1 = SomeObject()
>>> so2 = SomeObject()
>>> so1.b is so2.b
True
>>> so1.b is SomeObject.b
True

Make b 一个实例属性:

Make b an instance attribute:

>>> import copy
>>> class SomeObject:
...     a = 1
...     def __init__(self):
...         self.b = {1: 1, 2: 2}
... 
>>> so1 = SomeObject()
>>> so2 = copy.deepcopy(so1)
>>> so1.b is so2.b
False

这篇关于使用deepcopy与字典里面的对象的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 07:42