python析构函数用法及注意事项
作者:小妮浅浅 时间:2023-01-25 19:53:11
1、主动删除对象调用del 对象;程序运行结束后,python也会自动进行删除其他的对象。
class Animal:
def __del__(self):
print("销毁对象{0}".format(self))
cat = Animal()
cat2 = Animal()
del cat2
print("程序结束")
2、如果重写子类的del方法,则必须显式调用父类的del方法,这样才能保证在回收子类对象时,其占用的资源(可能包含继承自父类的部分资源)能被彻底释放。
class Animal:
def __del__(self):
print("调用父类 __del__() 方法")
class Bird(Animal):
def __del__(self):
# super(Bird,self).__del__() #方法1:显示调用父类的del方法
print("调用子类 __del__() 方法")
cat = Bird()
#del cat #只能调用子类里面的__del__
#super(Bird,cat).__del__() #方法2:显示调用父类的__del__
函数实例扩展:
#coding=utf-8
'''
魔法方法,被__双下划线所包围
在适当的时候自动被调用
'''
#构造init、析构del
class Rectangle:
def __init__(self,x,y):
self.x = x
self.y = y
print('构造')
'''
del析构函数,并不是在del a对象的时候就会调用该析构函数
只有当该对象的引用计数为0时才会调用析构函数,回收资源
析构函数被python的垃圾回收器销毁的时候调用。当某一个对象没有被引用时,垃圾回收器自动回收资源,调用析构函数
'''
def __del__(self):
print('析构')
def getPeri(self):
return (self.x + self.y)*2
def getArea(self):
return self.x * self.y
if __name__ == '__main__':
rect = Rectangle(3,4)
# a = rect.getArea()
# b = rect.getPeri()
# print(a,b)
rect1 = rect
del rect1
# del rect
while 1:
pass
来源:https://www.py.cn/jishu/jichu/31132.html
标签:python,析构函数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
php版微信支付api.mch.weixin.qq.com域名解析慢原因与解决方法
2023-07-16 11:36:01
细化解析:SQL Server 2005 数据库镜像
2009-01-23 13:41:00
如何使用 SQL Server 数据库查询累计值
2008-12-03 15:27:00
Python入门教程(三十九)Python的NumPy安装与入门
2023-08-25 10:38:30
![](https://img.aspxhome.com/file/2023/2/82822_0s.png)
用ASP打造一个小型的网页BBS系统
2008-10-10 16:36:00
Vue.js实现微信过渡动画左右切换效果
2023-07-02 17:03:10
![](https://img.aspxhome.com/file/2023/4/139904_0s.gif)
实例详解Python中的numpy.abs和abs函数
2023-03-09 08:06:38
python pandas query的使用方法
2023-01-14 06:23:33
Python图像的增强处理操作示例【基于ImageEnhance类】
2022-02-12 04:31:46
![](https://img.aspxhome.com/file/2023/3/127883_0s.jpg)
Python实现自动化域名批量解析分享
2023-01-27 00:04:36
![](https://img.aspxhome.com/file/2023/2/75172_0s.png)
python 装饰器功能以及函数参数使用介绍
2022-04-03 05:12:32
![](https://img.aspxhome.com/file/2023/4/67794_0s.png)
在VSCode中添加Python解释器并安装Python库的方法
2022-04-21 19:13:53
![](https://img.aspxhome.com/file/2023/1/112431_0s.png)
使用pycharm将自己项目代码上传github(小白教程)
2022-05-02 20:37:06
![](https://img.aspxhome.com/file/2023/6/82526_0s.jpg)
Flask 入门系列 Cookie与session的介绍
2022-06-21 00:45:44
![](https://img.aspxhome.com/file/2023/9/103769_0s.png)
Python3安装tensorflow及配置过程
2021-04-07 01:47:09
![](https://img.aspxhome.com/file/2023/2/81662_0s.jpg)
Python基础之类的定义和使用详解
2023-03-10 08:23:34
![](https://img.aspxhome.com/file/2023/0/95800_0s.png)
golang指数运算操作
2024-01-30 22:35:53
Go语言转换所有字符串为大写或者小写的方法
2023-06-21 19:48:07
python调用ffmpeg命令行工具便捷操作视频示例实现过程
2023-12-19 07:48:22
Python 实现自动登录+点击+滑动验证功能
2023-10-09 01:11:05
![](https://img.aspxhome.com/file/2023/1/118791_0s.jpg)