import sys
class A():
def __init__(self):
'''初始化對象'''
print('object born id:%s' %str(hex(id(self))))
def f1():
'''循環(huán)引用變量與刪除變量'''
while True:
c1=A()
del c1
def func(c):
print('obejct refcount is: ',sys.getrefcount(c)) #getrefcount()方法用于返回對象的引用計(jì)數(shù)
if __name__ == '__main__':
#生成對象
a=A() # 此時為1
#del a # 如果del,下一句會報錯, = 0,被清理
print('obejct refcount is: ', sys.getrefcount(a)) # 此時為2 getrefcount是一個函數(shù) +1
func(a)
#增加引用
b=a
func(a)
#銷毀引用對象b
del b
func(a)
執(zhí)行結(jié)果:
object born id:0x7f9abe8f2128
obejct refcount is: 2
obejct refcount is: 4
obejct refcount is: 5
obejct refcount is: 4
導(dǎo)致引用計(jì)數(shù) +1 的情況
對象被創(chuàng)建,例如 a=23
對象被引用,例如 b=a
對象被作為參數(shù),傳入到一個函數(shù)中,例如func(a)
對象作為一個元素,存儲在容器中,例如list1=[a,a]
導(dǎo)致引用計(jì)數(shù)-1 的情況
對象的別名被顯式銷毀,例如del a
對象的別名被賦予新的對象,例如a=24
一個對象離開它的作用域,例如 f 函數(shù)執(zhí)行完畢時,func函數(shù)中的局部變量(全局變量不會)
對象所在的容器被銷毀,或從容器中刪除對象
循環(huán)引用導(dǎo)致內(nèi)存泄露
def f2():
'''循環(huán)引用'''
while True:
c1=A()
c2=A()
c1.t=c2
c2.t=c1
del c1
del c2
執(zhí)行結(jié)果
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
...