python析構函數(shù)用法及注意事項
更新時間:2021年06月22日 08:15:20 作者:小妮淺淺
在本篇文章里小編給大家整理的是一篇關于python析構函數(shù)用法及注意事項,有需要的朋友們可以學習參考下。
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__
函數(shù)實例擴展:
#coding=utf-8 ''' 魔法方法,被__雙下劃線所包圍 在適當?shù)臅r候自動被調用 ''' #構造init、析構del class Rectangle: def __init__(self,x,y): self.x = x self.y = y print('構造') ''' del析構函數(shù),并不是在del a對象的時候就會調用該析構函數(shù) 只有當該對象的引用計數(shù)為0時才會調用析構函數(shù),回收資源 析構函數(shù)被python的垃圾回收器銷毀的時候調用。當某一個對象沒有被引用時,垃圾回收器自動回收資源,調用析構函數(shù) ''' 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析構函數(shù)用法及注意事項的文章就介紹到這了,更多相關python析構函數(shù)的使用注意內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
在Python程序和Flask框架中使用SQLAlchemy的教程
SQLAlchemy為Python程序與SQL語句之間建立了映射,是Python操作數(shù)據(jù)庫的利器,這里我們將來看在Python程序和Flask框架中使用SQLAlchemy的教程,需要的朋友可以參考下2016-06-06