我有一个超类,它具有一个由其子类共享的方法。但是,此方法应返回具有在子类上定义的类型的对象。我希望方法的返回类型是静态注释的(不是动态类型),因此使用子类的代码可以从mypy
返回值的类型检查中受益。但是我不想仅仅为了提供其类型注释而在子类上重新定义通用方法。python类型注释和mypy是否可能?
像这样:
from typing import Type
class AbstractModel:
pass
class OrderModel(AbstractModel):
def do_order_stuff():
pass
class AbstractRepository:
model: Type[AbstractModel]
def get(self) -> model:
return self.model()
class OrderRepository(AbstractRepository):
model = OrderModel
repo = OrderRepository()
order = repo.get()
# Type checkers (like mypy) should recognize that this is valid
order.do_order_stuff()
# Type checkers should complain about this; because `OrderModel`
# does not define `foo`
order.foo()
棘手的动作是get()
在超类上定义的AbstractRepository
,它尚不知道的类型model
。(并且-> model
注释失败,因为model
尚未指定的值)。
的值model
由子类指定,但子类并未(重新)定义get()
以提供注释。看来这应该是静态可分析的;尽管这有些棘手,但因为它需要静态分析器才能跟踪model
从超类到子类的引用。
有什么办法可以实现共享的超类实现和精确的子类返回类型?
定义AbstractRepository
为通用类。
from typing import TypeVar, Generic, Type, ClassVar
T = TypeVar('T')
class AbstractRespotitory(Generic[T]):
model: ClassVar[Type[T]]
@classmethod
def get(cls) -> T:
return cls.model()
(get
仅使用class属性,因此可以并且可以说应该是class方法。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句