當物件被銷毀時呼叫析構函數。在Python中,析構函數不像在c 中那麼需要,因為Python有一個垃圾收集器,可以自動處理記憶體管理。 __del__()方法在Python中稱為析構函數方法。當對物件的所有參考都已被刪除時即當一個物件被垃圾回收時,將呼叫該函數。
析構函數宣告的語法:
def __del__(self): # body of destructor
範例1:下面是析構函數的簡單範例。透過使用del關鍵字刪除物件「obj」的所有引用,從而自動呼叫析構函數。
# Python program to illustrate destructor
class Employee:
# Initializing
def __init__(self):
print('Employee created.')
# Deleting (Calling destructor)
def __del__(self):
print('Destructor called, Employee deleted.')
obj = Employee()
del obj輸出:
Employee created. Destructor called, Employee deleted.
注意:析構函數是在程式結束後呼叫的,或是當對物件的所有參考都被刪除時呼叫的。當引用計數為零時,而不是當物件超出範圍時。
例2:這個例子解釋了上述的注意事項。這裡,注意析構函數是在「Program End…」列印之後呼叫的。
# Python program to illustrate destructor
class Employee:
# Initializing
def __init__(self):
print('Employee created')
# Calling destructor
def __del__(self):
print("Destructor called")
def Create_obj():
print('Making Object...')
obj = Employee()
print('function end...')
return obj
print('Calling Create_obj() function...')
obj = Create_obj()
print('Program End...')#輸出:
Calling Create_obj() function... Making Object... Employee created function end... Program End... Destructor called
例3:現在,考慮下面的範例:
# Python program to illustrate destructor
class A:
def __init__(self, bb):
self.b = bb
class B:
def __init__(self):
self.a = A(self)
def __del__(self):
print("die")
def fun():
b = B()
fun()輸出:
die
在這個範例中,當函數fun()被呼叫時,它建立了一個B類實例,它將自身傳遞給A類,然後A類設定對B類的參考並產生循環引用。
通常,用於檢測這些類型的循環引用的Python的垃圾收集器會將其刪除,但在此範例中,使用自訂析構函數將此項標記為「uncollectable」(無法收集)。
簡單地說,它不知道銷毀物件的順序,因此它會離開它們。因此,如果您的實例涉及循環引用,則只要應用程式運行,它們就會存在記憶體中。
相關推薦:《Python教學》
以上是Python中的析構函數詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!