If I run this code, I'v got the subject error message. But why? And how to avoid it getting the C
class having its parents slots?
class A():
__slots__ = ['slot1']
class B():
__slots__ = ['slot2']
class C(A, B):
__slots__ = []
It had (in my opinion) a silly workaround. That's why no
TypeError
is raised when__slots__
is empty, and having an empty__slots__
attribute preserves the "wondered" python behaviour what warns when assigning to an attribute not defined in__slots__
.So, consider the following metaclass:
An then deploy on base classes.
If we execute following code
This produces following output
Simply speak, you just cannot do it.
As stated in Documentation,
The idea behind
__slots__
is to reserve specific slots for each attribute in the memory layout of your instances.A
andB
are trying to reserve the same part of their memory layout for theslot1
andslot2
attributes, andC
can't have the same memory reserved for two attributes. It's just not compatible.Thanks for JCode metioned in comment, the following method is modified to be correct.
But there is always the way, I personally prefer to use a common base contained all required slots if
__slots__
is necessary while there is multiple inherited class.Update The 4 values will be 88, 88, 88, 312. Though
__slots__
reserved.