1. 程式人生 > >Python拾遺之特殊函式 __del__

Python拾遺之特殊函式 __del__

當刪除最後一個物件時,python直譯器會預設呼叫一個方法,這個方法為_ del ()方法。在python中,很少會直接銷燬物件,如果需要,一般使用del關鍵字銷燬。Python的記憶體管理機制能夠很好的勝任這份工作。不管是手動呼叫del還是由python自動回收都會觸發 del _方法執行

# -*- coding: utf-8 -*-

import sys


class Test(object):

    def __init__(self):
        print '__init__'

    def __del__(self):
        print
'__del__' if __name__ == '__main__': a = Test() print(sys.getrefcount(a)) """結果為 __init__ 2 __del__ """