侧边栏壁纸
博主头像
我的学习心得 博主等级

行动起来,活在当下

  • 累计撰写 223 篇文章
  • 累计创建 60 个标签
  • 累计收到 4 条评论

目 录CONTENT

文章目录

typing.ClassVar

Administrator
2024-09-20 / 0 评论 / 0 点赞 / 310 阅读 / 0 字
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

评论区