在python中实现weakref属性的描述符类

weakref_propert的Python项目详细描述


添加一个类似于普通属性的属性, 但对指定的任何内容都保持弱引用 为了它。

示例:

First let’s define WeakValue using WeakProperty and SomeClass that will be weakly referenced:

>>> import weakref_property
>>> import gc

>>> class WeakValue(object):
...     value = weakref_property.WeakProperty('value')

>>> class SomeClass(object):
...     pass

You can assign and retrieve a value:

>>> a = SomeClass()
>>> obj = WeakValue()
>>> obj.value = a
>>> obj.value  # doctest: +ELLIPSIS
<__main__.SomeClass object at ...>

But it is kept as a weakref, so it can get collected. If it is collected, the property returns None:

>>> del a
>>> gc.collect()  # force gc to collect `a` object
0
>>> obj.value

You can also delete the value completelly:

>>> del obj.value
>>> obj.value
Traceback (most recent call last):
    ...
AttributeError: 'WeakValue' object has no attribute 'value'

Sadly, weakrefs do not work on tuples, ints and not-subclassed lists and dicts:

>>> obj.value = []
Traceback (most recent call last):
    ...
TypeError: cannot create weak reference to 'list' object

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
c#Java Tcp服务器和。Net Tcp客户端的发送和接收问题   安卓应用程序上的java标记地理位置,其位置位于我周围5Km半径范围内。   向java添加对话框并检索html文件   当eclipse甚至无法打开时,java会在eclipse中更改不兼容的JVM   java中同一jframe中的jlabel和paintComponent   基于另一数组排序的java排序   java AADSTS7000012:该补助金是为另一个租户获得的   java在JSF中使用foreach循环   java如何通过maven为运行junit测试创建运行配置?   java Selenium webDriver不稳定错误堆栈跟踪   java有没有办法创建以键为大写的JSON对象?