Issue Using Deepcopy With Dictionary Inside Object
Reading the documentation, I understood that copy.deepcopy(obj) copies recursively any other object inside this one, but when I run: >>> import copy >>> class Som
Solution 1:
Deepcopy only copies instance attributes. Your b
attribute is a class attribute, instead.
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
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
Post a Comment for "Issue Using Deepcopy With Dictionary Inside Object"