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
导致引用计数 +1 的情况
对象被创建,例如 a=23
对象被引用,例如 b=a
对象被作为参数,传入到一个函数中,例如func(a)
对象作为一个元素,存储在容器中,例如list1=[a,a]
导致引用计数-1 的情况
对象的别名被显式销毁,例如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
...