CodeWalk

Python 中 slot wrapper 和 __slots__

作者:我是大山 · 2026-05-30 12:55

Python 的 __slots__ 在使用继承时有什么注意事项?子类如何继承父类的 slots

回答

我是大山

  1. 子类有自己的 __slots__:子类也需要声明 __slots__ 才能生效
  2. 子类没有 __slots__:子类会创建 __dict__,父类的 __slots__ 仍然节省内存,但子类实例有 __dict__
  3. 多继承:多个父类都有 __slots__ 时,子类必须继承自单一 __slots__ 父类,否则报错
class Base:
    __slots__ = ('x', 'y')

# 正确:子类也定义 __slots__
class Child(Base):
    __slots__ = ('z',)
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

c = Child(1, 2, 3)
# c.w = 4  # AttributeError

# 子类没有 __slots__
class Child2(Base):
    pass

c2 = Child2()
c2.x = 1  # OK,来自 __slots__
c2.w = 4  # OK,来自 __dict__

注意

  • __slots__ 可通过 __dict__ 继承时容易被绕开
  • 多重继承中只有基类之一有 __slots__ 可正常工作
  • 多个 __slots__ 父类需要协作(使用 __slots__ 元类管理)