Kindly explain this source code for me

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 1K views
user366312
Gold Member
Messages
88
Reaction score
3
TL;DR
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?

[CODE lang="python" title="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)
[/CODE]

The following is the output of the above source code:

Output:
[CODE lang="python" title="Output"]
init
11 [2, 3, 4, 5]
11 [2, 3, 4]
[/CODE]

Why is 11 not changed into 12?

Why is element 5 missing the 3rd line?
 
Last edited:
Physics news on Phys.org
This is actually quite involved for a beginner question.

If you are the one who has added the questions in comments, I can see your questions don't start with copy or deepcopy, but how classes and methods are declared. How familiar are you wth Python syntax?
 
Reply
  • Like
Likes   Reactions: jim mcnamara and berkeman
Start from here:
Here is the basic syntax - which you can compare to your sample.
https://docs.python.org/3/library/copy.html

But, the way your question is written might imply that you should consider -

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
The difference is whether a reference to the original object (using a pointer) is created. Or the original(s) itself gets its very own copy. Why would this be useful?
 
Reply
  • Informative
Likes   Reactions: jack action