Python special methods in common - del Method

__del __ () method for the destruction of Python object - at the time of any Python objects collected by the system, the system will automatically call this method. But do not think that del perform operations on a variable, the variable is referenced objects will be recovered, of course not, if there are multiple variables refer to it, is not one of the variables del reclaim the object.

Chestnuts as follows:

. 1  # Coding. 8 = UTF- 
2  class Item:
 . 3      DEF  the __init__ (Self, name,. Price):
 . 4          the self.name = name
 . 5          self.price = . Price
 . 6      DEF  the __del__ (Self):
 . 7          Print ( ' del method for deleting objects ' )
 8  # Create an Item object, it will be assigned to the variable 
. 9 it = Item ( ' mouse ' , 29.8 )
 10 X = it
 . 11  # printing it Item object referenced 
12 is  del it
 13 is print('----------')

Print Console as follows:

 

Explanation: The first line of code rewrite 6,7 __del __ class Item () method, the system will be recovered when the Item, the system automatically calls __del __ () method of the Item object. The above program first creates an Item object and the object is assigned to the variable it, turn it on line 10 of code assigned to x, so the program has two variables refer to the Item object, and then the routine del it objects to delete it, At this time, since there is a variable that references the Item object, so that the program does not recover Item object. It will be seen as the output of the above, why is this so? Because after del it, the program does not recover Item object, only to wait until the program is about to end (the system must recover all of the objects), the system will recover Item objects. If the code comment line 10, is printed as follows:

Explanation: Note Thereafter, when the program is executed del it, this time in the program no longer has any variable reference Item object, so the object will be recovered immediately, without waiting for the end of the program.

Guess you like

Origin www.cnblogs.com/tizer/p/11183945.html