简体   繁体   English

如何在 python 中定义 final classvar 变量

[英]How to define final classvar variable in python

As you can see in PEP 526 we can define static variable class with ClassVar word.正如您在PEP 526中看到的,我们可以使用 ClassVar 字定义 static 变量 class 。 like below像下面

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

And another typing feature as you can see in PEP 591 we can define constant (readonly) variable with Final word, like below您可以在PEP 591中看到另一个打字功能,我们可以使用 Final word 定义常量(只读)变量,如下所示

class Connection:
    TIMEOUT: Final[int] = 10

My question is how to combine these two words to say my class static variable is Final?我的问题是如何结合这两个词说我的 class static 变量是最终的?

for example is below code is valid?例如下面的代码是否有效?

class Connection:
    TIMEOUT: Final[ClassVar[int]] = 10

From PEP-591 :来自PEP-591

Type checkers should infer a final attribute that is initialized in a class body as being a class variable.类型检查器应将在 class 主体中初始化的最终属性推断为 class 变量。 Variables should not be annotated with both ClassVar and Final.变量不应同时使用 ClassVar 和 Final 进行注释。

So you ca just use:所以你可以使用:

class Connection:
    TIMEOUT: Final[int] = 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM