Python析构函数__del__定义原理解析
作者:yoyo008 时间:2023-01-02 15:20:29
析构函数__del__定义:在类里定义,如果不定义,Python 会在后台提供默认析构函数。
析构函数__del__调用:
A、使用del 显式的调用析构函数删除对象时:del对象名;
class Foo:
def __init__(self,x):
self.x=x
def __del__(self): #在对象资源被释放时触发
print('-----del------')
print(self)
f=Foo(100000)
del f
B、当对象在某个作用域中调用完毕,跳出其作用域的同时析构函数也会被调用一次,这样可以用来释放内存空间。
class Foo:
def __init__(self,x):
self.x=x
def __del__(self): #在对象资源被释放时触发
print('-----del------')
print(self)
f=Foo(100000)
time.sleep(5) #time.sleep(5)执行完后,自动调用__del__()
注意:__del__只是删除了对象的引用,比如上面del f 只是f对象不再执行实例数据的存储空间了,实例数据并没有被删除,删除实例数据需要python本身的垃圾回收机制;
垃圾回收机制
Python 采用垃圾回收机制来清理不再使用的对象;Python 提供gc模块释放不再使用的对象,Python 采用‘引用计数' 的算法方式来处理回收,
即:当某个对象在其作用域内不再被其他对象引用的时候,Python 就自动清除对象;
Python 的函数collect()可以一次性收集所有待处理的对象(gc.collect())
来源:https://www.cnblogs.com/yoyo008/p/9602962.html
标签:python,垃圾,回收,析构,函数,del
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python 中创建 PostgreSQL 数据库连接池
2024-01-19 22:33:37
Python流程控制语句详解
2022-03-01 22:36:37
![](https://img.aspxhome.com/file/2023/0/92370_0s.jpg)
python机器学习包mlxtend的安装和配置详解
2021-11-09 22:53:06
![](https://img.aspxhome.com/file/2023/3/135373_0s.png)
从MySQL得到最大的优化性能
2024-01-20 20:22:08
4款Python 类型检查工具,你选择哪个呢?
2021-10-29 22:30:27
![](https://img.aspxhome.com/file/2023/4/92424_0s.png)
MySQL 使用SQL语句修改表名的实现
2024-01-17 09:14:31
![](https://img.aspxhome.com/file/2023/1/121541_0s.jpg)
pycharm如何为函数插入文档注释
2023-09-13 09:53:56
![](https://img.aspxhome.com/file/2023/3/133553_0s.png)
如何在scrapy中捕获并处理各种异常
2023-04-10 06:56:23
![](https://img.aspxhome.com/file/2023/2/100922_0s.png)
Go语言参数传递是传值还是传引用
2024-02-20 02:32:34
![](https://img.aspxhome.com/file/2023/0/105120_0s.png)
Python 高级专用类方法的实例详解
2023-10-11 14:13:52
ORACLE数据库查看执行计划的方法
2012-06-06 20:15:52
mysql数据库优化需要遵守的原则
2024-01-15 13:54:29
Python Web框架之Django框架Form组件用法详解
2021-10-21 11:12:39
ms SQL server数据库备份、压缩与SQL数据库数据处理的方法
2024-01-18 14:54:04
Python对于json数据键值对遍历
2023-02-21 06:01:08
Python按键或值对字典进行排序
2021-01-02 10:45:52
Win7环境下搭建Go开发环境(基于VSCode编辑器)
2024-04-30 09:59:04
![](https://img.aspxhome.com/file/2023/0/130920_0s.png)
python列表元素拼接成字符串的4种方法
2021-10-02 23:59:59
Python 元组(Tuple)操作详解
2023-06-28 15:36:39
![](https://img.aspxhome.com/file/2023/3/59133_0s.png)
ASP用JAVASCRIPT脚本实现分页的办法
2007-10-30 13:18:00