使用 pydantic + Mixins 模式的 ABC/接口问题

问题描述

我正在尝试实现 Mixin 模式,同时我使用 Pydantics BaseClass 来促进我的类中数据的实例化和验证。问题是我的 Mixins 不能从我的基类继承(实际上,依赖是相反的)。另外,我使用的是 mypy,所以我的实现需要正确输入。

让我们看一个简化的例子:

class BaseCart(BaseModel):
    id: int
    items: List[Item]
    adress: str


class CartInterface(ABC):
    @abstractproperty
    def id(self):
        ...

    @abstractproperty
    def items(self):
        ...

    @abstractproperty
    def adress(self):
        ...

    @abstractmethod
    def get_shipping_value(self):
        ...

    @abstractmethod
    def get_items_availability(self):
        ...


class ShippingMixin(ABC,CartInterface):
    def get_shipping_value(self) -> int:
        # some business logic using self.address to calculate

class normalItemsMixin(ABC,CartInterface):
    def get_items_availability(self) -> bool:
       # iterate over self.items and check stock availability

class AwesomeItemsMixin(ABC,CartInterface):
    def get_items_availability(self) -> bool:
       # iterate over self.items and check stock availability
       # this implementation is different from the normal one

class normalCart(BaseCart,ShippingMixin,normalItemsMixin):
    ...

class AwesomeCart(BaseCart,AwesomeItemsMixin):
    ...

问题是在实现这个之后,我无法实例化AwesomeCart,我收到以下错误TypeError: Can't instantiate abstract class ResellerCart with abstract methods business_unit,cart_type,channel,id,items,reseller,status,updated_at

我错过了什么?

TLDR:为什么会这样


class Data(BaseModel):
    a: int

class IData(ABC):
    @abstractproperty
    def a(self):
        ...

class XData(Data,IData):
    ...

当我实例化TypeError: Can't instantiate abstract class XData with abstract method a喜欢XData时加注x = XData(a=1)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)