如何解决具有可覆盖的静态属性的抽象类注释
我有抽象类:
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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。