用戶調用析構器來銷毀對象。在 Python 中,開發人員可能不像在 C++語言中那樣需要析構器。這是因為 Python 有一個垃圾收集器,它的功能是自動處理內存管理。
在本文中,我們將討論 Python 中的析構器是如何工作的,以及用戶何時可以使用它們。
del() 函數在 Python 中用作析構器。當對象的所有引用都被刪除,變成垃圾收集時,用戶可以調用 del() 函數。
語法:
def __del__(self):
    # the body of destructor will be written here. 
用戶還應該注意,當對象超出引用或代碼結束時,對對象的引用也會被刪除。
在下面的例子中,我們將使用 del()函數和 del 關鍵字刪除對象的所有引用,這樣析構器將自動涉及。
例如:
# we will illustrate destructor function in Python program
# we will create Class named Animals
class Animals:
    #  we will initialize the class
    def __init__(self):
        print('The class called Animals is CREATED.')
    # now, we will Call the destructor
    def __del__(self):
        print('The destructor is called for deleting the Animals.')
object = Animals()
del object 
輸出:
The class called Animals is CREATED.
The destructor is called for deleting the Animals.
解釋-
在上面的代碼中,當對象的引用被刪除或者程序結束後,析構器已經被調用。這意味着對象的引用計數變為零,而不是當對象超出範圍時。我們將通過展示下一個例子來解釋這一點。
我們還可以注意到,析構器是在程序結束後調用的。
示例:
# We will create Class named Animals
class Animals:
    #  Initialize the class
    def __init__(self):
        print('The class called Animals is CREATED.')
    # now, we will Call the destructor
    def __del__(self):
        print('The destructor is called for deleting the Animals.')
def Create_object():
    print('we are creating the object')
    object = Animals()
    print('we are ending the function here')
    return object
print('we are calling the Create_object() function now')
object = Create_object()
print('The Program is ending here')
輸出:
we are calling the Create_object() function now
we are creating the object
The class called Animals is CREATED.
we are ending the function here
The Program is ending here
The destructor is called for deleting the Animals.
現在,在下一個示例中,我們將看到,當調用函數()時,它將創建類 Zebra 的實例,該實例將自身傳遞給類 Lion,然後類 Lion 將設置對類 Zebra 的引用,這將導致循環引用。
示例:
class Animals:
    #  we will initialize the class
    def __init__(self):
        print(' The class called Animals is CREATED.')
class Lion:
    def __init__(self, zebraa):
        self.zebra = zebraa
class Zebra:
    def __init__(self):
        self.lion = Lion(self)
    def __del__(self):
        print("Zebra is dead")
def function():
    zebra = Zebra()
function()
輸出:
Zebra is dead
一般來說,Python 的垃圾收集器(用於檢測這些類型的循環引用)也會移除引用。但是,在上面的例子中,自定義析構器被用來將這個項目標記為無法收集。
用簡單的語言來說,它意味着垃圾收集器不知道對象應該被銷毀的順序,所以它離開了它們。因此,如果用戶的實例包含在這個循環引用中,只要應用運行,它們就會一直存儲在內存中。
結論
在本文中,我們解釋了 Python 中析構器的功能,以及用戶如何使用它們來刪除那些引用已經從內存中移除的對象。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/240256.html
微信掃一掃 
支付寶掃一掃