python 7-7 如何在环状数据结构中管理内存,标准库中的weakref,创建一种能访问对象但不能增加引用计数的对象

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().

>>> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值