"""演示可复用校验描述符与 __set_name__。""" from __future__ import annotations from typing import Any class Validated: """类型 + 范围校验的数据描述符。""" def __init__( self, expected: type, *, minimum: int | float | None = None, maximum: int | float | None = None, ) -> None: self.expected = expected self.minimum = minimum self.maximum = maximum self.name = "" def __set_name__(self, owner: type, name: str) -> None: self.name = name def __get__(self, obj: Any, objtype: type | None = None) -> Any: if obj is None: return self return obj.__dict__[self.name] def __set__(self, obj: Any, value: Any) -> None: if not isinstance(value, self.expected): raise TypeError( f"{self.name} must be {self.expected.__name__}, got {type(value).__name__}" ) if self.minimum is not None and isinstance(value, int | float) and value < self.minimum: raise ValueError(f"{self.name} must be >= {self.minimum}") if self.maximum is not None and isinstance(value, int | float) and value > self.maximum: raise ValueError(f"{self.name} must be <= {self.maximum}") obj.__dict__[self.name] = value class Product: name = Validated(str) price = Validated(int, minimum=0, maximum=10000) def __init__(self, name: str, price: int) -> None: self.name = name self.price = price def main() -> None: product = Product("Widget", 99) print(f"names: {Product.name.name}, {Product.price.name}") print(f"product: {product.name} {product.price}") try: product.price = "99" # 演示运行时类型校验 except TypeError as exc: print(f"type error: {exc}") try: product.price = 20000 except ValueError as exc: print(f"range error: {exc}") print(f"class access: {type(Product.price).__name__}") if __name__ == "__main__": main()