You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Python类的__annotations__中生成__slots__是否存在弊端?

从Python类的__annotations__中生成__slots__是否存在弊端?

用过Python类型注解的朋友应该都碰到过这种情况:当类里声明了__slots__时,属性名往往要重复写两遍——一遍在类型注解里,一遍在__slots__的元组里,显得有点啰嗦。举个简单例子:

class Event:
    location: tuple[float, float]
    index: int

    __slots__ = (
        "location",
        "index",
    )

为了避免这种重复劳动,有人想出了一个办法:直接利用类的__annotations__来生成__slots__,写法如下:

class Event:
    location: tuple[float, float]
    index: int

    __slots__ = tuple(__annotations__)

那问题来了:在Python 3.10及更高版本中,这种从__annotations__推导__slots__的做法,有没有什么需要注意的弊端,或者说有没有什么场景下应该避免这么做呢?


补充说明:

  • 这种写法曾被作为解决方案,用来解决和__slots__类型注解相关的问题
  • 之前也有过类似的讨论:“用__annotations__.keys()来定义__slots__是不是好实践?”,不过我在提问的时候并没有意识到这个讨论的存在

备注:内容来源于stack exchange,提问作者ideasman42

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 18:18:00