python中的弱引用 [英] Weak References in python

查看:51
本文介绍了python中的弱引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试了解 python 弱引用列表/字典的工作原理.我已经阅读了它的文档,但是我无法弄清楚它们是如何工作的,以及它们的用途.谁能给我一个他们所做工作的基本示例以及他们如何工作的解释?

I have been trying to understand how python weak reference lists/dictionaries work. I've read the documentation for it, however I cannot figure out how they work, and what they can be used for. Could anyone give me a basic example of what they do and an explanation of how they work?

(EDIT) 使用 Thomas 的代码,当我用 obj 替换 [1,2,3] 它抛出:

(EDIT) Using Thomas's code, when i substitute obj for [1,2,3] it throws:

Traceback (most recent call last):
File "C:/Users/nonya/Desktop/test.py", line 9, in <module>
r = weakref.ref(obj)
TypeError: cannot create weak reference to 'list' object

推荐答案

理论

引用计数通常是这样工作的:每次创建对对象的引用时,它都会加一,每当删除一个引用时,它就会减一.

Theory

The reference count usually works as such: each time you create a reference to an object, it is increased by one, and whenever you delete a reference, it is decreased by one.

弱引用允许您创建对不会增加引用计数的对象的引用.

Weak references allow you to create references to an object that will not increase the reference count.

python 的垃圾收集器在运行时使用引用计数:任何引用计数为 0 的对象都将被垃圾收集.

The reference count is used by python's Garbage Collector when it runs: any object whose reference count is 0 will be garbage collected.

你会为昂贵的对象使用弱引用,或者避免循环引用(尽管垃圾收集器通常自己做).

You would use weak references for expensive objects, or to avoid circle references (although the garbage collector usually does it on its own).

这是一个演示其用法的工作示例:

Here's a working example demonstrating their usage:

import weakref
import gc

class MyObject(object):
    def my_method(self):
        print 'my_method was called!'

obj = MyObject()
r = weakref.ref(obj)

gc.collect()
assert r() is obj #r() allows you to access the object referenced: it's there.

obj = 1 #Let's change what obj references to
gc.collect()
assert r() is None #There is no object left: it was gc'ed.

这篇关于python中的弱引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆