问题
This is explicitly documented in the reference manual:
Nonempty __slots__ does not work for classes derived from “variable-length” built-in types such as int, bytes and tuple.
and it is the case, writing:
class MyInt(int):
__slots__ = 'spam',
results in:
TypeError: nonempty __slots__ not supported for subtype of 'int'
why is this, though? Why can empty slots be used but non empty ones fobidden?
回答1:
__slots__
reserves space at a fixed offset in an object’s layout for each slot defined. (This is how it avoids having a __dict__
in which to store them.) A variable-length object could have a fixed-length prefix before its variable-size data, but when deriving from such a type there’s no available fixed offset at which to add a slot. Since part of the purpose of __slots__
is fast lookup, it doesn’t make much sense to teach it how to look past the end of the variable-length data. __dict__
, however, does have such support, so it’s meaningful to suppress it with __slots__=()
.
来源:https://stackoverflow.com/questions/44725110/why-cant-nonempty-slots-be-used-with-int-tuple-bytes-subclasses