如何在 python 中定义最终的 classvar 变量
How to define final classvar variable in python
正如你在PEP 526中看到的,我们可以用ClassVar word定义静态变量class。如下图
class Starship:
stats: ClassVar[dict[str, int]] = {} # class variable
damage: int = 10 # instance variable
还有另一个打字功能,您可以在 PEP 591 中看到,我们可以使用 Final word 定义常量(只读)变量,如下所示
class Connection:
TIMEOUT: Final[int] = 10
我的问题是如何将这两个词组合起来说我的 class 静态变量是 Final?
例如下面的代码是否有效?
class Connection:
TIMEOUT: Final[ClassVar[int]] = 10
来自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
正如你在PEP 526中看到的,我们可以用ClassVar word定义静态变量class。如下图
class Starship:
stats: ClassVar[dict[str, int]] = {} # class variable
damage: int = 10 # instance variable
还有另一个打字功能,您可以在 PEP 591 中看到,我们可以使用 Final word 定义常量(只读)变量,如下所示
class Connection:
TIMEOUT: Final[int] = 10
我的问题是如何将这两个词组合起来说我的 class 静态变量是 Final?
例如下面的代码是否有效?
class Connection:
TIMEOUT: Final[ClassVar[int]] = 10
来自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