- #1
user366312
Gold Member
- 89
- 3
- TL;DR Summary
- The following source code is collected from stackoverflow.com. It demonstrates the design pattern to implement shallow copy and deep copy.
Check this link: How to override the copy/deep-copy operations for a Python object?
Can anyone explain, in layman's terms, what is going on in this source code?
The following is the output of the above source code:
Output:
Why is 11 not changed into 12?
Why is element 5 missing the 3rd line?
Can anyone explain, in layman's terms, what is going on in this source code?
copy functions in python:
from copy import copy, deepcopy
class MyClass(object):
def __init__(self):
print('init')
self.v = 10
self.z = [2, 3, 4]
def __copy__(self): # why doesn't this function take any argument?
cls = self.__class__ # Python equivalent of C++'s "this"-pointer
result = cls.__new__(cls) # Python equivalent of C++'s static constructor. Why is it explicitly invoked here?
result.__dict__.update(self.__dict__) # updating data-type information
return result
def __deepcopy__(self, memo): # what is memo? why is it needed?
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result # what is going on here?
for k, v in self.__dict__.items():
setattr(result, k, deepcopy(v)) # what is going on here?
return result
a = MyClass()
a.v = 11
b1 = copy(a) # why is this being called without object 'a'?
b2 = deepcopy(a)# why is this being called without object 'a'?
a.v = 12
a.z.append(5)
print(b1.v, b1.z)
print(b2.v, b2.z)
print(b2.v, b2.z)
The following is the output of the above source code:
Output:
Output:
init
11 [2, 3, 4, 5]
11 [2, 3, 4]
Why is 11 not changed into 12?
Why is element 5 missing the 3rd line?
Last edited: