python __del__() 清空對象
python垃圾回收機制:當一個對象的引用被完全清空之后,就會調用__del__()方法來清空這個對象
當對象的引用沒有被完全清空時,代碼如下:
class C(): def __init__(self): print('調用構造器創建對象') def __del__(self): print('銷毀創建的對象') c1 = C() c2 = c1 c3 = c1 print('=====================================') print(str(id(c1)) +' , '+ str(id(c2)) +' , '+ str(id(c3))) print('=====================================') del c1 del c2 # del c3 先保留c3,不完全刪除C()的引用 # print(c1) 不注釋的話會報錯:NameError: name 'c1' is not defined # print(c2) 不注釋的話會報錯:NameError: name 'c2' is not defined print(c3) # 輸出:<__main__.C object at 0x0000023444AF0AC0> print('=====================================') while True: time.sleep(2) print('循環中.......')
輸出結果: 下面的輸出結果里面沒有顯示 “銷毀創建的對象”
調用構造器創建對象 ===================================== 2423513877184 , 2423513877184 , 2423513877184 ===================================== <__main__.C object at 0x0000023444AF0AC0> ===================================== 循環中....... 循環中....... 循環中....... 循環中.......
當對象的引用完全被清空時,代碼如下:
class C(): def __init__(self): print('調用構造器創建對象') def __del__(self): print('銷毀創建的對象') c1 = C() c2 = c1 c3 = c1 print('=====================================') print(str(id(c1)) +' , '+ str(id(c2)) +' , '+ str(id(c3))) print('=====================================') del c1 del c2 del c3 #已經將對象的引用全部刪除,程序會自動調用 __del__方法 # print(c1) 不注釋的話會報錯:NameError: name 'c1' is not defined # print(c2) 不注釋的話會報錯:NameError: name 'c2' is not defined # print(c3) 不注釋的話會報錯:NameError: name 'c3' is not defined print('=====================================') while True: time.sleep(2) print('循環中.......')
輸出結果:
調用構造器創建對象 ===================================== 2873013504704 , 2873013504704 , 2873013504704 ===================================== 銷毀創建的對象 ===================================== 循環中....... 循環中....... 循環中....... 循環中.......