Code前端首页关于Code前端联系我们

Python 中的析构函数

terry 2年前 (2023-09-29) 阅读数 63 #PHP
文章标签 PHP

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


版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

热门