1、主動刪除對象調用del 對象;程序運行結束后,python也會自動進行刪除其他的對象。
class Animal:
def __del__(self):
print("銷毀對象{0}".format(self))
cat = Animal()
cat2 = Animal()
del cat2
print("程序結束")
2、如果重寫子類的del方法,則必須顯式調用父類的del方法,這樣才能保證在回收子類對象時,其占用的資源(可能包含繼承自父類的部分資源)能被徹底釋放。
class Animal:
def __del__(self):
print("調用父類 __del__() 方法")
class Bird(Animal):
def __del__(self):
# super(Bird,self).__del__() #方法1:顯示調用父類的del方法
print("調用子類 __del__() 方法")
cat = Bird()
#del cat #只能調用子類里面的__del__
#super(Bird,cat).__del__() #方法2:顯示調用父類的__del__
函數實例擴展:
#coding=utf-8
'''
魔法方法,被__雙下劃線所包圍
在適當的時候自動被調用
'''
#構造init、析構del
class Rectangle:
def __init__(self,x,y):
self.x = x
self.y = y
print('構造')
'''
del析構函數,并不是在del a對象的時候就會調用該析構函數
只有當該對象的引用計數為0時才會調用析構函數,回收資源
析構函數被python的垃圾回收器銷毀的時候調用。當某一個對象沒有被引用時,垃圾回收器自動回收資源,調用析構函數
'''
def __del__(self):
print('析構')
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
到此這篇關于python析構函數用法及注意事項的文章就介紹到這了,更多相關python析構函數的使用注意內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python函數不定長參數使用方法解析
- Python函數中不定長參數的寫法
- Python中函數的定義及其調用
- 這三個好用的python函數你不能不知道!
- Python函數中的不定長參數相關知識總結