本文摘自php中文网,作者藏色散人,侵删。
当对象被销毁时调用析构函数。在Python中,析构函数不像在c++中那么需要,因为Python有一个垃圾收集器,可以自动处理内存管理。__del__()方法在Python中称为析构函数方法。当对对象的所有引用都已被删除时即当一个对象被垃圾回收时,将调用该函数。析构函数声明的语法:
1 2 | def __del__(self):
# body of destructor
|
例1:下面是析构函数的简单示例。通过使用del关键字删除对象“obj”的所有引用,从而自动调用析构函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 | # 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
|
输出:
1 2 | Employee created.
Destructor called, Employee deleted.
|
注意:析构函数是在程序结束后调用的,或者当对对象的所有引用都被删除时调用的。当引用计数为零时,而不是当对象超出范围时。
例2:这个例子解释了上面提到的注意事项。这里,注意析构函数是在“Program End…”打印之后调用的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # 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...' )
|
输出:
1 2 3 4 5 6 | Calling Create_obj() function ...
Making Object...
Employee created
function end ...
Program End ...
Destructor called
|
例3:现在,考虑下面的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # 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()
|
输出:
在这个示例中,当函数fun()被调用时,它创建了一个B类实例,它将自身传递给A类,然后A类设置对B类的引用并产生循环引用。
通常,用于检测这些类型的循环引用的Python的垃圾收集器会将其删除,但在此示例中,使用自定义析构函数将此项标记为“uncollectable”(无法收集)。
简单地说,它不知道销毁对象的顺序,因此它会离开它们。因此,如果您的实例涉及循环引用,则只要应用程序运行,它们就会存在内存中。
相关推荐:《Python教程》
以上就是Python中的析构函数详解的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python能做什么项目
Python环境变量如何配置
Python中subprocess库的用法介绍
Python简单实现控制电脑的方法
Python如何利用itertools.groupby() 根据字段将记录分组
Python如何对指定字符串逆序
Python怎么安装pandas
Python如何求一组数的最大值?
网络编程详细介绍
从青铜到王者,进阶数据可视化2.0的五个Python库!
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python中的析构函数详解