在Python中的析构函数

在Python中的析构函数

用户调用析构函数以销毁对象。在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中解构函数的功能以及用户如何使用它们来删除已经从内存中删除引用的对象。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程