如何在python中定义最终的classvar变量

2024-09-30 08:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

正如您在PEP 526中所看到的,我们可以用ClassVar word定义静态变量类。如下

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

另一个键入功能,正如您在PEP 591中看到的,我们可以用Final word定义常量(只读)变量,如下所示

class Connection:
    TIMEOUT: Final[int] = 10

我的问题是如何结合这两个词来表示我的类静态变量是Final

例如下面的代码是否有效

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

Tags: 定义statstimeout静态connectionvariabledictpep
1条回答
网友
1楼 · 发布于 2024-09-30 08:22:13

PEP-591

Type checkers should infer a final attribute that is initialized in a class body as being a class variable. Variables should not be annotated with both ClassVar and Final.

所以你可以使用:

class Connection:
    TIMEOUT: Final[int] = 10

相关问题 更多 >

    热门问题