[英]Can a child class inherit its base class root validators in pydantic?
我正在制作一个程序,我需要在其中定义大量具有相似结构的类。 但它们都有一个共同点:它们的变量必须检查一些条件。 所以我应该用它们的共同点定义一个父 class。
最重要的是,我希望每个孩子 class 能够定义一个无法初始化的“常量”:
我真的不知道如何解释自己,所以这里有一个写得非常糟糕且无法正常运行的代码示例来说明我的意图:
这是一家为超过 10 欧元的商品提供折扣的商店。 所有书籍都有 10% 的折扣,所有手机都有 15% 的折扣,依此类推。
from pydantic import BaseModel, root_validator
class ShopItems(BaseModel):
price: float
discount: float
def get_final_price(self) -> float: #All shop item classes should inherit this function
return self.price * (1 - self.discount/100)
@root_validator(pre=True)
def discount_validator(cls, values): #They should also inherit this one as a validator
if values["price"] < 10
values["discount"] = 0
return values
class Book(ShopItems):
price: float #I want to be able to set a different price for any book
discount = 10
class Phone(ShopItems):
price: float
discount = 15
book1 = Book(price=42) #This one should have discount
book2 = Book(8) #This one shouldn't
book1.get_final_price()
book2.get_final_price()
我也不应该在定义书籍折扣时更改它。 书籍的折扣价值应该被冻结。
我试过使用数据类,但我真的不知道如何将 pydantic 的验证器与数据类合并。
默认情况下,验证器将被继承。 但是您需要对代码应用许多修复:
from pydantic import BaseModel, root_validator
class ShopItems(BaseModel):
price: float
discount: float
def get_final_price(self) -> float: #All shop item classes should inherit this function
return self.price * (1 - self.discount/100)
@root_validator(pre=True)
def discount_validator(cls, values): #They should also inherit this one as a validator
if values["price"] < 10:
values["discount"] = 0
return values
class Book(ShopItems):
discount = 10.
class Phone(ShopItems):
discount = 15.
book1 = Book(price=42) #This one should have discount
book2 = Book(price=8) #This one shouldn't
print(repr(book1), book1.get_final_price())
print(repr(book2), book2.get_final_price())
Book(price=42.0, discount=10.0) 37.800000000000004
Book(price=8.0, discount=0.0) 8.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.