Usage of python Destructor and Points for Attention
- 2021-11-13 02:13:58
- OfStack
1. Actively delete objects and call del objects; After the program runs, python will automatically delete other objects.
class Animal:
def __del__(self):
print(" Destroy object {0}".format(self))
cat = Animal()
cat2 = Animal()
del cat2
print(" End of program ")
2. If the del method of a subclass is overridden, the del method of the parent class must be explicitly called, so as to ensure that the resources occupied by the subclass object (which may include some resources inherited from the parent class) can be completely released when the subclass object is recycled.
class Animal:
def __del__(self):
print(" Call parent class __del__() Method ")
class Bird(Animal):
def __del__(self):
# super(Bird,self).__del__() # Method 1 Object that calls the parent class del Method
print(" Call subclass __del__() Method ")
cat = Bird()
#del cat # You can only call the __del__
#super(Bird,cat).__del__() # Method 2 Object that calls the parent class __del__
Function instance extension:
#coding=utf-8
'''
Magic method, by __ Surrounded by double underscores
Automatically invoked when appropriate
'''
# Structure init Destructing del
class Rectangle:
def __init__(self,x,y):
self.x = x
self.y = y
print(' Structure ')
'''
del Destructor, not in the del a The destructor is called when the
Only if the reference count of the object is 0 The destructor is called to recycle resources
Destructor is python Called when the garbage collector of is destroyed. When a 1 When an object is not referenced, the garbage collector automatically reclaims the resource and calls the destructor
'''
def __del__(self):
print(' Destructing ')
def getPeri(self):
return (self.x + self.y)*2
def getArea(self):
return self.x * self.y
if __name__ == '__main__':
rect = Rectangle(3,4)
# a = rect.getArea()
# b = rect.getPeri()
# print(a,b)
rect1 = rect
del rect1
# del rect
while 1:
pass