实现说明
活动部件是类 PriceBand、Inventory和函数 __post_init__。
在这里做循环的是 for bad in (PriceBand(-1, 5), PriceBand(9, 3))。代码不会带着坏状态静默继续,守卫一命中就抛 ValueError、TypeError。
使用要点
- 守卫
self.low < 0 or self.high < 0命中后立刻用提前的raise结束这一轮。 - 每一步打印都带着自己的标签:
rejected:。
常见问题
前置条件不成立会发生什么?
代码会拒绝继续:抛出 ValueError、TypeError,此时状态仍可恢复。
运行「Dataclass 后置校验不变量」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 rejected: 标签标明各步骤。
主签名形如 def __post_init__(self) -> None
核心语句
def __post_init__(self) -> None:
if not isinstance(self.items, tuple):
# 可变默认值是坑:强制调用方传 tuple
raise TypeError('items must be a tuple of PriceBand')
except ValueError as exc:
print('rejected:', exc)
代码示例
from dataclasses import dataclass, field
@dataclass(frozen=True)
class PriceBand:
low: int
high: int
label: str = field(default='')
def __post_init__(self) -> None:
# 冻结实例的跨字段不变量在构造时一次锁定
if self.low < 0 or self.high < 0:
raise ValueError(f'prices must be non-negative: {self.low}..{self.high}')
if self.low > self.high:
raise ValueError(f'inverted band: {self.low} > {self.high}')
if not self.label:
object.__setattr__(self, 'label', f'{self.low}-{self.high}')
@dataclass(frozen=True)
class Inventory:
items: tuple[PriceBand, ...] = ()
def __post_init__(self) -> None:
if not isinstance(self.items, tuple):
# 可变默认值是坑:强制调用方传 tuple
raise TypeError('items must be a tuple of PriceBand')
if __name__ == '__main__':
band = PriceBand(100, 500)
print(band.label)
for bad in (PriceBand(-1, 5), PriceBand(9, 3)):
try:
bad
except ValueError as exc:
print('rejected:', exc)
inventory = Inventory(items=(band,))
print(inventory)