def all_nodes(self): yield self n = self.other while n and n.name != self.name: yield n n = n.other if n is self: yield n return
所以,即使手动调用了 a = None, b = None, c = None,对象也不会被删除
Garbage:[ ,
,
,
{'name': 'one', 'other': },
{'name': 'two', 'other': },
{'name': 'three', 'other': }]
而弱引用是指“引用一个对象,但并不增加被引用对象的指针计数”
可以通过c = weekref.ref(k,func)
来指定引用的对象及对象删除后的动作func
调用时,使用c() 来引用k
但是在上个例子里面,我们需要一个“代理对象”来代理这个被引用的对象,从而使set_next 函数对于变量other可以同正常变量一样使用
def set_next(self, other): if other is not None: if self in other.all_nodes(): other = weakref.proxy(other) super(WeakGraph, self).set_next(other) return
从而避免了通过other()来引用一个other对象~
查看更多关于python图自身遍历及弱引用使用的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did86699