Why can't nonempty slots be used with int, tuple, bytes subclasses?

爱⌒轻易说出口 提交于 2020-01-14 03:43:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!