簡體   English   中英

一個孩子 class 可以繼承它在 pydantic 中的基礎 class 根驗證器嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM