I tried to use weak references on my classes, where I use slots to save some memory, but I wasn't able to make derived class.
class A(object):
__slots__ = ['__weakref__']
class B(A):
__slots__ = A.__slots__ + ['foo']
#TypeError: Error when calling the metaclass bases
# __weakref__ slot disallowed: either we already got one, or __itemsize__ != 0
Where's the trick? I didn't find any solution. I'm using python 2.7.3.
In derived classes you should not put slots that were defined in the base classes.
In fact the error says:
TypeError
: Error when calling the metaclass bases__weakref__
slot disallowed: either we already got one, or__itemsize__ != 0
Simply use:
class B(A):
__slots__ = ['foo']
This is explained in the documentation for__slots__
:
The action of a
__slots__
declaration is limited to the class where it is defined. As a result, subclasses will have a__dict__
unless they also define__slots__
(which must only contain names of any additional slots).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With