Python對象中__del__方法起作用的條件詳解


對象的__del__是對象在被gc消除回收的時候起作用的一個方法,它的執行一般也就意味着對象不能夠繼續引用。

示范代碼如下:

?
1
2
3
4
5
6
7
8
9
class Demo:
 
def __del__( self ):
 
   print ( "calling __del__" )
  
obj = Demo()
 
del obj

程序執行結果如下:

?
1
2
3
grey@DESKTOP - 3T80NPQ : / mnt / e / 01_workspace / 02_programme_language / 03_python / 03_OOP / 2017 / 08 $python del_method.py
 
calling __del__

但是,這並不是讓__del__執行的唯一方式。其實,這個方法也可以直接調用。測試代碼如下:

?
1
2
3
4
5
6
7
8
9
class Demo:
 
def __init__( self ):
 
   print ( "calling __del__" )
 
obj = Demo()
 
obj.__del__()

程序執行結果:

?
1
2
3
grey@DESKTOP - 3T80NPQ : / mnt / e / 01_workspace / 02_programme_language / 03_python / 03_OOP / 2017 / 08 $python del_method.py
 
calling __del__

但是,這樣的執行很多時候並不能夠保證垃圾回收的正常執行。

如下代碼:

?
1
2
3
4
5
grey@DESKTOP - 3T80NPQ : / mnt / e / 01_workspace / 02_programme_language / 03_python / 03_OOP / 2017 / 08 $python del_method.py
 
calling __del__
 
calling __del__

執行結果:

?
1
2
3
4
5
grey@DESKTOP - 3T80NPQ : / mnt / e / 01_workspace / 02_programme_language / 03_python / 03_OOP / 2017 / 08 $python del_method.py
 
calling __del__
 
calling __del__

推測:上面的刪除方法觸發了兩次刪除,但是由於引用關系,刪除銷毀其實沒有實現。

修改代碼驗證如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Demo:
 
def __del__( self ):
 
   print ( "calling __del__" )
 
   del self
 
  
 
obj = Demo()
 
obj.__del__()
 
print ( id (obj))

執行結果:

?
1
2
3
4
5
6
7
grey@DESKTOP - 3T80NPQ : / mnt / e / 01_workspace / 02_programme_language / 03_python / 03_OOP / 2017 / 08 $python del_method.py
 
calling __del__
 
140726800222040
 
calling __del__

從上面看來,其實主要還有對對象的引用,這個銷毀的動作還是需要等待對象引用沒有了以后才能夠完成。進一步驗證代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Demo:
 
def __del__( self ):
 
   print ( "calling __del__" )
 
   del self
 
  
 
obj = Demo()
 
obj.__del__()
 
print ( id (obj))
 
print ( id (obj))

執行結果:

?
1
2
3
4
5
6
7
8
9
grey@DESKTOP - 3T80NPQ : / mnt / e / 01_workspace / 02_programme_language / 03_python / 03_OOP / 2017 / 08 $python del_method.py
 
calling __del__
 
140568015406936
 
140568015406936
 
calling __del__

從上面結果看,猜測還是准確的。

 

 

 
[Python] Python Web開發—進階提升 490集超強Python視頻教程
[Python] 智普教育 python就業班 視頻教程 教學視頻 百度網盤下載
2017Python運維WEB開發全站工程師系列視頻教程
Python實戰 四周實現爬蟲網站 視頻教程 教學視頻 百度網盤下載(價值499元)  ...2
Python高級編程技巧實戰 基於Python項目與面試題講解 視頻教程 教學視頻
Python運維工程師#12期視頻系列學習教程
老男孩Python高級全棧開發工程師全套 視頻教程 教學視頻 百度網盤下載  ...2
老男孩python第六期高級運維開發課程編程實戰精品入門進階完整版 24G
老王Python基礎,進階,項目篇(無KEY完整版) 視頻教程 15G
麥子學院招牌課程[明星python編程視頻教程][22G](價值9000元)百度網盤下載  ...2
2017python就業班百度雲在線分享 attach_img
麥子學院 Python基礎+Pythonweb+Python擴展+Python選修四大專題 視頻j教程 35G
老男孩python開發視頻教程,超級經典,一學就會
2017最新全棧python第2期系列視頻教程#92Day attach_img
[Python] Python零基礎入門學習視頻教程全42集百度雲網盤下載
[Python] 老男孩python自動化運維視頻教程(全9集)
[Python] Python Web開發 全50集 視頻教程 教學視頻
[Python] 利用Python SOCKET多線程開發FTP軟件 全6集 視頻教程 教學視頻
[Python] Python.Django 13集 視頻教程 教學視頻


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM