如何在Python中銷燬物件?
當物件被刪除或銷燬時,會呼叫解構函式。在終止物件之前,會使用解構函式完成清理任務,例如關閉資料庫連線或檔案控制代碼。
Python中的垃圾回收器自動管理記憶體。例如,當物件不再相關時,它會清除記憶體。
在Python中,解構函式是完全自動的,絕不會手動呼叫。在以下兩種情況下,會呼叫解構函式:
- 當物件不再相關或超出作用域時
- 物件的引用計數達到零。
使用__del__()方法
在Python中,解構函式使用特定的函式__del__()定義。例如,當我們執行del 物件名時,物件的解構函式會自動呼叫,然後它會被垃圾回收。
示例1
以下是使用__del__()方法的解構函式示例:
# creating a class named destructor class destructor: # initializing the class def __init__(self): print ("Object gets created"); # calling the destructor def __del__(self): print ("Object gets destroyed"); # create an object Object = destructor(); # deleting the object del Object;
輸出
以下是上述程式碼的輸出:
Object gets created Object gets destroyed
注意 - 上述程式碼中的解構函式在程式執行結束或刪除對物件的引用後被呼叫。這表明物件的引用計數現在降為零,而不是當它離開作用域時。
示例2
在下面的示例中,我們將使用Python的del關鍵字來銷燬使用者定義的物件:
class destructor: Numbers = 10 def formatNumbers(self): return "@" + str(Numbers) del destructor print(destructor)
輸出
以下是上述程式碼的輸出:
NameError: name 'destructor' is not defined
我們得到上述錯誤,因為“解構函式”被銷燬了。
示例3
在下面的示例中,我們將看到:
- 如何使用解構函式
- 當我們刪除物件時,解構函式是如何被呼叫的?
class destructor: # using constructor def __init__(self, name): print('Inside the Constructor') self.name = name print('Object gets initialized') def show(self): print('The name is', self.name) # using destructor def __del__(self): print('Inside the destructor') print('Object gets destroyed') # creating an object d = destructor('Destroyed') d.show() # deleting the object del d
輸出
我們使用上面的程式碼建立了一個物件。一個名為d的引用變數用於標識新生成的物件。當對物件的引用被銷燬或其引用計數為0時,解構函式已被呼叫。
Inside the Constructor Object gets initialized The name is Destroyed Inside the destructor Object gets destroyed
關於解構函式需要注意的事項
- 當物件的引用計數達到0時,將為該物件呼叫__del__方法。
- 當應用程式關閉或我們使用del關鍵字手動刪除所有引用時,該物件的引用計數將降為零。
- 當我們刪除物件引用時,解構函式不會被呼叫。它要等到對所有物件的引用都被刪除後才會執行。
示例
讓我們用這個例子來理解上面提到的原則:
- 使用d = destructor("Destroyed"),首先為student類建立一個物件。
- 接下來,使用d1=d將物件引用d賦給新物件d1。
- 現在,同一個物件由d和d1變數引用。
- 之後,我們刪除了引用d。
- 為了理解解構函式僅在刪除對物件的所有引用時才起作用,我們在主執行緒中添加了10秒的睡眠時間。
import time class destructor: # using constructor def __init__(self, name): print('Inside the Constructor') self.name = name print('Object gets initialized') def show(self): print('The name is', self.name) # using destructor def __del__(self): print('Inside the destructor') print('Object gets destroyed') # creating an object d = destructor('Destroyed') # Creating a new reference where both the reference points to same object d1=d d.show() # deleting the object d del d # adding sleep and observing the output time.sleep(10) print('After sleeping for 10 seconds') d1.show()
輸出
正如您在輸出中看到的,解構函式只在刪除對所有物件的引用後才被呼叫。
此外,一旦程式執行結束並且物件已準備好進行垃圾回收,就會呼叫解構函式。(也就是說,我們沒有顯式使用del d1來刪除物件引用d1)。
Inside the Constructor Object gets initialized The name is Destroyed After sleeping for 10 seconds The name is Destroyed
廣告