In this article, let's look at the Python object Destruction (garbage collection), for a friend who has just come into contact with the Python programming language, the knowledge of the Python object Destruction (garbage collection) should be relatively small, and it is unclear
Python garbage collectionKnowledge of this aspect. But it's okay, in the next article we'll look at the knowledge of Python object destruction (garbage collection), and
garbage collection mechanism in Python。
Python Object Destruction (garbage collection)
Python uses the simple technique of reference counting to track and recycle garbage.
Inside Python is a record of how many references each object in use has.
An internal tracking variable, called a reference counter.
When the object is created, a reference count is created, and when the object is no longer needed, that is, the reference count of the object becomes 0 o'clock, and it is garbage collected. However, recycling is not "immediate", and the interpreter uses the garbage object to reclaim the memory space at the appropriate time.
A = + # Create object <40>b = A # Add reference, <40> count C = [b] # Add Reference. <40> Count del a # reduce the count of references <40> B = # # Reduce the reference <40> count c[0] =-1 # Reduce the count of references <40>
The garbage collection mechanism not only targets objects with a reference count of 0, but can also handle circular references. Circular references refer to two of objects referencing each other, but no other variables refer to them.
In this case, using only the reference count is not enough. The Python garbage collector is actually a reference counter and a cyclic garbage collector. As a supplement to the reference count, the garbage collector also pays attention to objects that are allocated a large amount (and those that are not destroyed by reference counting). In this case, the interpreter pauses to attempt to clean up all unreferenced loops.
Example analysis
destructor __del__, __del__ is called when the object is destroyed, and the __del__ method runs when the object is no longer being used:
#!/usr/bin/python#-*-coding:utf-8-*-class point: def __init__ (self, x=0, y=0): self.x = x self.y = y def __del__ (self): class_name = self.__class__.__name__ print class_name, "destroy" pt1 = point () pt2 = PT1PT3 = pt 1print ID (PT1), id (PT2), id (PT3) # Print Object Iddel pt1del Pt2del pt3
The results of the above example operation are as follows:
3083401324 3083401324 3083401324Point Destruction
(Note: Usually you need to define a class in a separate file.)