【问题标题】:Can a child class inherit its base class root validators in pydantic?子类可以在 pydantic 中继承其基类根验证器吗?
【发布时间】:2021-08-14 20:01:28
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: python pydantic


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2017-02-21
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多