擅长:python、mysql、java
<blockquote>
<p>Without a <code>__weakref__</code> variable for each instance, classes defining <code>__slots__</code> do not support weak references to its instances. If weak reference support is needed, then add <code>__weakref__</code> to the sequence of strings in the <code>__slots__</code> declaration.</p>
</blockquote>
<p>从<a href="http://docs.python.org/2/reference/datamodel.html#slots" rel="noreferrer">Python documentation</a>开始。在</p>
<p>如果将<code>__weakref__</code>添加到<code>__slots__</code>,则代码将正常工作:</p>
<pre><code>>>> 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 ...>
</code></pre>