例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Demo: def __init__( self , i): self .i = i def __str__( self ): return str ( self .i) def __del__( self ): print ( "bye-bye " + self .__str__()) def hello( self ): print ( "hello " + self .__str__()) a = Demo( 22 ) a.hello() a = Demo( 33 ) a.hello() a = Demo( 44 ) a.hello() a = Demo( 55 ) a.hello() # 《程式語言教學誌》的範例程式 # 檔名:delm01.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 12 月 |
執行結果如下

第 8 行到第 9 行,這裡是 __del__() 定義的地方
8 9 | def __del__( self ): print ( "bye-bye " + self .__str__()) |
我們只有使用變數 (variable) a 一個名稱,利用建構子 Demo() 建立物件後呼叫 hello() ,然後重新呼叫 Demo() 建立另一個 Demo 型態的物件,我們可以看到直譯器主動呼叫 __del__() ,印出 "bye-bye" 的訊息。
最後程式結束執行前,直譯器同樣主動呼叫最後建立物件解構子,完全釋放所使用的記憶體空間。
中英文術語對照 | |
---|---|
建構子 | constructor |
物件 | object |
直譯器 | interpreter |
方法 | method |
解構子 | destructor |
改寫 | override |
變數 | variable |
參考資料
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/compound_stmts.html
http://docs.python.org/py3k/reference/datamodel.html
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/compound_stmts.html
http://docs.python.org/py3k/reference/datamodel.html
沒有留言:
張貼留言