首页 > 解决方案 > 子类可以在 pydantic 中继承其基类根验证器吗?

问题描述

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

最重要的是,我希望每个子类都能够定义一个无法初始化的“常量”:

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

这是一家为超过 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 的验证器与数据类合并。

标签: pythonpydantic

解决方案


默认情况下将继承验证器。但是您需要对代码进行一些修复:

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

推荐阅读