侧边栏壁纸
  • 累计撰写 218 篇文章
  • 累计创建 59 个标签
  • 累计收到 5 条评论

typing.ClassVar

barwe
2024-09-20 / 0 评论 / 0 点赞 / 180 阅读 / 639 字
温馨提示:
本文最后更新于 2024-09-20,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
from typing import ClassVar

用法:

class Starship:
    stats: ClassVar[dict[str, int]] = {} # class variable
    damage: int = 10                     # instance variable

ClassVar 用于指示一个变量是类变量而非实例变量,从而提高代码的可读性。

ClassVar 仅用于类型注解,不影响程序执行。

ClassVar 本身不是一个类,不能用于 isinstance() 或者 issubclass() 方法。

以下为原文:

Special type construct to mark class variables.

An annotation wrapped in ClassVar indicates that a given
attribute is intended to be used as a class variable and
should not be set on instances of that class.

Usage::

class Starship:
stats: ClassVar[dict[str, int]] = {} # class variable
damage: int = 10                     # instance variable

ClassVar accepts only types and cannot be further subscribed.

Note that ClassVar is not a class itself, and should not
be used with isinstance() or issubclass().
0

评论区