当对象被销毁时调用析构函数。在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 createdfunction 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教程》
以上就是python中的析构函数详解的详细内容。
