Weakref和\uuu槽__

2024-05-08 11:40:20 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下代码:

from weakref import ref

class Klass(object):
    # __slots__ = ['foo']
    def __init__(self):
        self.foo = 'bar'

k = Klass()
r = ref(k)

它可以工作,但是当我取消对__slots__的注释时,它在python2.6下以TypeError: "cannot create weak reference to 'Klass' object"中断。在

请问,有人知道这是Python和__slots__的固有限制还是一个bug?如何解决这个问题?在


Tags: 代码fromimportselfrefobjectfooinit
2条回答

您必须将__weakref__添加到插槽列表中。它是^{} quirks之一。在2.3之前,即使这样也不起作用,但幸运的是,您的版本没有那么旧。在

Without a __weakref__ variable for each instance, classes defining __slots__ do not support weak references to its instances. If weak reference support is needed, then add __weakref__ to the sequence of strings in the __slots__ declaration.

Python documentation开始。在

如果将__weakref__添加到__slots__,则代码将正常工作:

>>> from weakref import ref
>>>
>>> class Klass(object):
>>>     __slots__ = ['foo', '__weakref__']
>>>     def __init__(self):
>>>         self.foo = 'bar'
>>> k = Klass()
>>> k
 => <__main__.Klass object at ...>
>>> r = ref(k)
>>> r
 => <weakref at ...; to 'Klass' at ...>

相关问题 更多 >

    热门问题