我有一个带有特殊值“ 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
但是,棉绒,代码完成等不喜欢这种方式,因为它们不被视为类的静态属性。甚至设置它们也被报告为mypy错误,因此# type: ignore
。
下面的方法不起作用,因为我不能RealSet
在类范围内构造a ,因为它尚不存在:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句