1

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)

如果设置了变量的类型,是否可以检查它们?

4

1 回答 1

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)
于 2019-07-26T12:14:49.593 回答