子类可以在pydantic中继承其基类根验证器吗?



我正在编写一个程序,需要在其中定义大量具有类似结构的类。但它们都有一个共同点:它们的变量必须检查一些条件。所以我应该定义一个父类,包含它们的共同点。

最重要的是,我希望每个子类都能够定义一个"常量"。不能初始化:

我真的不知道如何解释我自己,所以这里有一个写得很差和没有功能的代码的例子,说明了我的意图:

这是一家商品超过10欧元有折扣的商店。所有的书打九折,所有的电话打八五折,以此类推。

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