如何从 int/str 派生出 __slots__?

How to derive from int/str with __slots__?

我需要从 int/str 派生一个 class 进行漂亮的打印,但是打印必须参数化,因此需要一个插槽。这会遇到 Python 限制,即从 int/str 派生的 classes 不能有非空槽。有人可以建议解决方法吗?

class HexDisplayedInteger(int):
    __slots__ = ["length"]

    def __str__(self):
        return format(self, "0%sX" % self.length)

这会产生一个错误:

_______________________________ ERROR collecting tests/lib/test_search.py _______________________________
tests/lib/test_search.py:1: in <module>
    from declarativeunittest import *
tests/declarativeunittest.py:5: in <module>
    from construct import *
construct/__init__.py:22: in <module>
    from construct.core import *
construct/core.py:2905: in <module>
    class HexDisplayedInteger(integertypes[0], object):
E   TypeError: Error when calling the metaclass bases
E       nonempty __slots__ not supported for subtype of 'long'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 13 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

啊我发现属性不需要在要添加的插槽中。现在我在想,我已经知道了,但是由于某种原因太习惯于定义插槽,以至于我忘记了它们不是强制性的。

class HexDisplayedInteger(int):
    def __str__(self):
        return format(self, "0%sX" % self.length)
  1. PyLongObject 是 CPython 实现中的可变长度 class,它将数字数组存储在其结构的末尾。
  2. __slots__ 在结构的末尾保留 space 并使用偏移量来检索它们,这是为了避免使用字典(__dict__)的开销。

综上所述,这两个冲突,由于PyLongObject及其派生是可变长度的,因此不可能reserve/retrieve具有固定偏移量的插槽。