pydantic模块仅在init中检查变量
pip install 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)
是否可以检查变量的类型(如果已设置)?
答案 0 :(得分:0)
是的,如果我对您的理解正确,那完全有可能:
from pydantic.dataclasses import dataclass
class Config:
validate_assignment = True
@dataclass(config=Config)
class Glass:
capacity_volume: float
occupied_volume: float
glass = Glass('300', '100')
print(glass)
#> Glass(capacity_volume=300.0, occupied_volume=100.0)
glass.capacity_volume = '400'
print(glass)
#> Glass(capacity_volume=400.0, occupied_volume=100.0)