垃圾回收机制

'''
垃圾回收机制
'''
import gc
print(gc.isenabled()) #判断了;垃圾回收机制是否开启
gc.enable()
print(gc.isenabled())
print(gc.get_threshold())  #返回的元组分别是 新生-消亡>多少进行垃圾检测,0代检测超过多少次开启0和1代检测,1代检测超过多少次开启0,1,2代一起检测

# 手动触发 gc.collect()
import objgraph
import gc
class Person():
    pass
class Pet():
    pass
p=Person()
q=Pet()
print(objgraph.count('Person'))
print(objgraph.count('Pet'))

p.pet=q
q.master=p
#双向引用使得普通的垃圾回收机制无法回收这两个变量
del p
del q
print(objgraph.count('Person'))
print(objgraph.count('Pet'))
gc.collect() #手动触发垃圾回收
print(objgraph.count('Person'))
print(objgraph.count('Pet'))

'''
弱引用 避免形成循环引用
'''
import weakref
class Person():
    pass
class Pet():
    pass
p=Person()
q=Pet()
print(objgraph.count('Person'))
print(objgraph.count('Pet'))

p.pet=q
q.master=weakref.ref(p)
del p
del q
print(objgraph.count('Person'))
print(objgraph.count('Pet'))

#第二种方法解决循环引用的问题:
import weakref
class Person():
    pass
class Pet():
    pass
p=Person()
q=Pet()
print(objgraph.count('Person'))
print(objgraph.count('Pet'))

p.pet=q
q.master=p

p.pet=None
del p
del q
print(objgraph.count('Person'))
print(objgraph.count('Pet'))

你可能感兴趣的:(Python,算法,python)