Python 官方文档:入门教程 => 点击学习
目录引用计数引用计数案例导致引用计数 +1 的情况导致引用计数-1 的情况循环引用导致内存泄露分代回收垃圾回收GC 模块常用函数:引用计数 python 语言默认采用的垃圾
import sys
class A():
def __init__(self):
'''初始化对象'''
print('object born id:%s' %str(hex(id(self))))
def f1():
'''循环引用变量与删除变量'''
while True:
c1=A()
del c1
def func(c):
print('obejct refcount is: ',sys.getrefcount(c)) #getrefcount()方法用于返回对象的引用计数
if __name__ == '__main__':
#生成对象
a=A() # 此时为1
#del a # 如果del,下一句会报错, = 0,被清理
print('obejct refcount is: ', sys.getrefcount(a)) # 此时为2 getrefcount是一个函数 +1
func(a)
#增加引用
b=a
func(a)
#销毁引用对象b
del b
func(a)
执行结果:
object born id:0x7f9abe8f2128
obejct refcount is: 2
obejct refcount is: 4
obejct refcount is: 5
obejct refcount is: 4
对象被创建,例如 a=23
对象被引用,例如 b=a
对象被作为参数,传入到一个函数中,例如func(a)
对象作为一个元素,存储在容器中,例如list1=[a,a]
对象的别名被显式销毁,例如del a
对象的别名被赋予新的对象,例如a=24
一个对象离开它的作用域,例如 f 函数执行完毕时,func函数中的局部变量(全局变量不会)
对象所在的容器被销毁,或从容器中删除对象
def f2():
'''循环引用'''
while True:
c1=A()
c2=A()
c1.t=c2
c2.t=c1
del c1
del c2
执行结果
id:0x1feb9f691d0
object born id:0x1feb9f69438
object born id:0x1feb9f690b8
object born id:0x1feb9f69d68
object born id:0x1feb9f690f0
object born id:0x1feb9f694e0
object born id:0x1feb9f69f60
object born id:0x1feb9f69eb8
object born id:0x1feb9f69128
object born id:0x1feb9f69c88
object born id:0x1feb9f69470
object born id:0x1feb9f69e48
object born id:0x1feb9f69ef0
object born id:0x1feb9f69dd8
object born id:0x1feb9f69e10
object born id:0x1feb9f69ac8
object born id:0x1feb9f69198
object born id:0x1feb9f69cf8
object born id:0x1feb9f69da0
object born id:0x1feb9f69c18
object born id:0x1feb9f69d30
object born id:0x1feb9f69ba8
...
有三种情况会触发垃圾回收:
1.调用gc.collect(),需要先导入gc模块。
2.当gc模块的计数器达到阀值的时候。
3.程序退出的时候。
gc 模块提供一个接口给开发者设置垃圾回收的选项。上面说到,采用引用计数的方法管理内存的一个缺陷是循环引用,而 gc 模块的一个主要功能就是解决循环引用的问题。
以上就是分析python垃圾回收机制原理的详细内容,更多关于python垃圾回收机制的资料请关注编程网其它相关文章!
--结束END--
本文标题: 分析python垃圾回收机制原理
本文链接: https://www.lsjlt.com/news/134826.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0