python - 使类常量的类型是它所在的类

标签 python python-3.8 python-class

我有一个具有特殊值“EMPTY”和“UNIVERSE”的 Python 类:

class RealSet:
    """Continuous open, half-open, and closed regions and discreet values of the Reals"""

    # implementation placeholder
    def __init__(self, intervals, *, canonicalize):
        pass

# Outside the class

RealSet.EMPTY = RealSet(tuple(), canonicalize=False)  # type: ignore
RealSet.UNIVERSE = RealSet(((None, None),), canonicalize=False)  # type: ignore

但是,linting、代码完成等不喜欢这样,因为它们不被视为类的静态属性。即使设置它们也会报告为 mypy 错误,因此 # type:ignore

下面的代码不起作用,因为我无法在类范围内构造 RealSet,因为它还不存在:

class RealSet:
    """Continuous open, half-open, and closed regions and discreet values of the Reals"""
    ...
    ...

    EMPTY = RealSet(tuple(), canonicalize=False)  # error
    UNIVERSE = RealSet(((None, None),), canonicalize=False)  # error

这不起作用,因为它定义了实例属性,而不是类属性:

class RealSet:
    """Continuous open, half-open, and closed regions and discreet values of the Reals"""
    ...
    ...

    EMPTY: "RealSet"
    UNIVERSE: "RealSet"

# Outside the class

RealSet.EMPTY = RealSet(tuple(), canonicalize=False)
RealSet.UNIVERSE = RealSet(((None, None),), canonicalize=False)

这似乎是 Python 类设计中的一个极端情况。如何创建类属性,其中属性的类型是它所在的类?奖励:使它们保持不变。

最佳答案

您可以使用typing.ClassVar注释类变量:

class RealSet:
    def __init__(self, intervals, *, canonicalize):
        pass

    EMPTY: ClassVar['RealSet']
    UNIVERSE: ClassVar['RealSet']


RealSet.EMPTY = RealSet(tuple(), canonicalize=False)
RealSet.UNIVERSE = RealSet(((None, None),), canonicalize=False)

关于python - 使类常量的类型是它所在的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66163768/

相关文章:

python - Pytube 只能定期工作(KeyError : 'assets' )

python - Python 中的函数链接,如果某个段返回 False,则忽略链的其余部分

python - 你能在每次修改另一个字段时修改一个对象的字段吗?

python - y 轴的刻度标签很长。如何在seaborn中截断它们?

python - Scikit 图像颜色过滤和将图像的部分更改为数组

pip - "conda install pip"更改 python 版本。如何避免这种情况?

python - 使用 Python3.8 安装新软件包时,如何修复 "module ' 平台'没有属性 'linux_distribution'”?

python - 为什么这个父类setter调用使用type(self)而不是self?

python - 如何在 Python 的抽象基类中合并类型检查

python - 在 python 中确定文本语言和纠正拼写错误的最佳算法是什么?