← 中文资源

简体中文版本

带初始化后校验的数据类

在数据类的初始化后钩子中校验不变式,使非法实例无法被构造,从源头阻止脏数据流入系统。

阅读英文原文

实现说明

逻辑集中在类 Money和函数 __post_init__、add里。 TypeError、ValueError 是守卫的信号——在分支处抛出,任何半成品工作之前。

使用要点

  • 守卫 not isinstance(self.amount, int) 成立时借助提前的 raise 直接离开。
  • 把 add 当作 API:导入它,其余代码可以忽略。

常见问题

这段代码会校验输入吗?

守卫处(not isinstance(self.amount, int))会抛出 TypeError、ValueError,非法状态到不了主逻辑。

这个示例需要哪些包?

一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 __post_init__、add。

主要签名是 def add(self, other: "Money") -> "Money"

核心语句

def add(self, other: "Money") -> "Money":
    if other.currency != self.currency:
        raise ValueError("cannot add different currencies")
    return Money(self.amount + other.amount, self.currency)

代码示例

from dataclasses import dataclass, field


@dataclass(frozen=True)
class Money:
    amount: int
    currency: str = "USD"

    def __post_init__(self) -> None:
        if not isinstance(self.amount, int):
            raise TypeError("amount must be an int number of minor units")
        if self.amount < 0:
            raise ValueError("amount must be non-negative")
        if self.currency not in {"USD", "EUR", "GBP"}:
            raise ValueError(f"unsupported currency: {self.currency}")

    def add(self, other: "Money") -> "Money":
        if other.currency != self.currency:
            raise ValueError("cannot add different currencies")
        return Money(self.amount + other.amount, self.currency)