python 7-7 如何在环状数据结构中管理内存,使用标准库中的weakref,创建一种能访问对象但不能增加引用计数的对象
解决方案:
使用标准库中的weakref,它可以创建一种能访问对象但不能增加引用计数的对象
wref=weakref.ref(owner) ==>当所有引用owner的对象都被delete了,wref就不会指向真实的对象了
a_wref = weakref.ref(a)
a4 = a_wref() a_wref 不会是对象计数器加一操作
import gc ==>导入gc 模块
当引用对象的次数达到零食后,python内核会自动回收这个对象,也就是会调用析构方法
import weakref
import sys
class A(object):
def __del__(self):
print 'in A.__del__'
a=A()
print sys.getrefcount(a)
a2=a
print sys.getrefcount(a)
a_wref = weakref.ref(a)
a4 = a_wref()
print sys.getrefcount(a)
del a2
del a
print "end.."
import weakref
class Data(object):
def __init__(self,value,owner):
self.owner = weakref.ref(owner)
self.value = value
def __str__(self):
return "%s's data value is %s"%(self.owner(),self.value)
def __del__(self):
print 'in Data.__del__'
class Node(object):
def __init__(self,value):
self.data = Data(value,self)
print self.data
def __del__(selfs):
print 'in Node.__del__'
node = Node(100)
del node
raw_input("waiting...")
help(sys.getrefcount)
>>> help(sys.getrefcount)
Help on built-in function getrefcount in module sys:
getrefcount(...)
getrefcount(object) -> integer
Return the reference count of object. The count returned is generally
one higher than you might expect, because it includes the (temporary)
reference as an argument to getrefcount().
>>>