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.
From the Python documentation.
If you add __weakref__
to __slots__
, your code will work:
>>> 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 ...>