pydantic 模块仅在 init 中检查变量
点安装 pydantic
例子
from pydantic.dataclasses import dataclass
@dataclass
class Glass:
capacity_volume : float
occupied_volume : float
glass = Glass(300, 100) # OK int to float
print(glass) # Glass(capacity_volume=500.0, occupied_volume=0.0)
glass = Glass(300.0, 100.0) # OK
print(glass) # Glass(capacity_volume=500.0, occupied_volume=0.0)
glass = Glass('300', '100') # OK str to float
print(glass) # Glass(capacity_volume=500.0, occupied_volume=0.0)
glass.capacity_volume = '300'
print(glass) # Glass(capacity_volume='300', occupied_volume=0.0)
如果设置了变量的类型,是否可以检查它们?