This time I will bring you the Objectlife cyclehow to use it during Pythoncopying, and the Notes on using Python to copy the object lifecycleWhat are they? The following is a practical case. Let’s take a look.
I don’t know much about Python’s shallow copy and deep copy. I don’t know if copy1 and copy2 in shutil are considered shallow copy and deep copy? Of these two operations, one is to reconstruct the fileattributes, and the other is to keep the file attributes unchanged. I wonder if the copying of objects can be compared to this?
Before copying, in order to watch the execution of GC, define a special class and object. The test code is as follows:
class Demo: def del(self): print("Removing{0}".format(id(self))) x = Demo() del x
The program execution results are as follows:
E:\01_workspace\02_programme_language\03_python\03_OOP\2017\08>pythoncopy1.py
Removing1772226785520
Next, construct an example of shallow copy:
>>>obj_list1 = [Demo(),Demo()] >>>obj_list2 = obj_list1[:] >>> del obj_list1 >>> del obj_list2 Removing1902510644416 Removing1902510644360
From the above results, the first del does not trigger the execution of the object destruction method. This is the result of debugging in the interactive interface. If the code is written to a specific file, the results of program execution may be different. When all statements are written to the same file, the scope of the objects in the file will be slightly adjusted. This deserves our attention.
Another common shallow copy method:
>>> o1 =o2 = Demo() >>> del o1 >>> del o2 Removing1902510136568
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How to read and write txt files line by line in python
How to batch read txt files into DataFrame in python Format
The above is the detailed content of How object lifecycle is used in Python replication. For more information, please follow other related articles on the PHP Chinese website!