From the python docs 3.3.2.4.1, it says "__slots__
declared in parents are available in child classes. However, child subclasses will get a __dict__
and __weakref__
unless they also define __slots__
(which should only contain names of any additional slots)."
However, while I was testing this as below:
class A(object):
__slots__ = ('a')
class B(A):
__slots__ = ('b')
b = B()
B.z = 'z'
B.a = 'a'
print(B.z) #z
print(B.a) #a
print(B.__dict__) #{'__module__': '__main__', '__slots__': ('b',), 'b': <member 'b' of 'B' objects>, '__doc__': None, 'z': 'z', 'a': 'a'}
Neither B.z
nor B.__dict__
throws exception, the code manages to output.
I am confused why the __slots__ = ('b')
in Class B
doesn't validate. Theoretically, it should throw an exception at B.z because the keys in slots don't contain it.
Could you please help to explain this strange point? And if possible, could you please help to provide the right usage method of slots in child classes?
By the way, my python version is 3.9.7
Thank you so much.