具有可覆盖的静态属性的抽象类注释

问题描述

我有抽象类:

import abc
from pydantic import BaseModel

class Abstract(abc.ABC):
    context_class: ClassVar[Type['BaseModel']]
    error: ClassVar[Type[Exception]]

    def __init__(self,data: Dict) -> None:
        self.context = self.context_class(**data)

    @abc.abstractmethod
    def process(self) -> None:
        pass

在继承者中,我覆盖了属性context_class

class Context(BaseModel):
    email: str

class Concrete(Abstract):
    context_class = Context

    def process(self) -> None:
        print(self.context.email)

Mypy检查失败,并显示以下错误:

... error: "BaseModel" has no attribute "email"

打包版本:

  • Python 3.8.2
  • Mypy 0.770
  • Pydantic 1.6.1

解决方法

最后,找到答案。应该使用通用类型:

import abc
from typing import ClassVar,Type,Dict,Generic,TypeVar
from pydantic import BaseModel

T = TypeVar('T',bound=BaseModel)


class Abstract(abc.ABC,Generic[T]):
    context_class: ClassVar[Type[T]]
    error: ClassVar[Type[Exception]]

    def __init__(self,data: Dict) -> None:
        self.context = self.context_class(**data)

    @abc.abstractmethod
    def process(self) -> None:
        pass


class Context(BaseModel):
    email: str


class Concrete(Abstract[Context]):
    context_class = Context

    def process(self) -> None:
        print(self.context.email)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...