当对象被销毁时调用析构函数。在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教程》