用户调用析构函数来销毁对象。在Python中,开发人员可能不需要像在C++语言中那样经常需要析构函数。这是因为Python具有垃圾收集器,其功能是自动处理内存管理。

在本文中,我们将讨论Python中的析构函数如何工作以及用户何时可以使用它们。

在Python中,del() 函数用作析构函数。当对象的所有引用都被删除并且它变为垃圾收集时,用户可以调用 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中析构函数的功能以及用户如何使用它们来删除已从内存中删除引用的对象。

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程