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().
评论区