Python Kindly explain this source code for me

AI Thread Summary
The discussion centers on overriding copy and deep-copy operations in Python using a custom class. The provided code defines a class, MyClass, which includes methods for shallow copying (__copy__) and deep copying (__deepcopy__). The __copy__ method creates a new instance of the class and copies the object's attributes without duplicating nested objects, while the __deepcopy__ method creates a new instance and recursively copies nested objects, utilizing a memo dictionary to track already copied objects to prevent infinite recursion.Key questions arise regarding the lack of parameters in the __copy__ method, the purpose of the memo in __deepcopy__, and why changes to the original object do not affect the copied objects. The output demonstrates that the shallow copy reflects changes to mutable objects, while the deep copy retains the original state of nested objects. The discussion emphasizes the importance of understanding the difference between shallow and deep copies, particularly in terms of object references versus actual copies, which is crucial for effective object manipulation in Python.
user366312
Gold Member
Messages
88
Reaction score
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?

[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:
Technology 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?
 
  • Like
Likes 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?
 
  • Informative
Likes jack action
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...

Similar threads

Replies
1
Views
4K
Replies
3
Views
2K
Replies
23
Views
2K
Replies
2
Views
2K
Replies
5
Views
2K
Replies
1
Views
1K
Back
Top