from typing import Type, TypeVar
T = TypeVar('T', bound='A')
class A:
@classmethod
def create(cls: Type[T]) -> T:
return cls()
class B(A):
def do(self):
...
@classmethod
def create(cls):
obj = super().create()
obj.do()
# ^^ <- complaint
if __name__ == '__main__':
b = B.create() # OK, no error
在上面的示例中,类型检查器抱怨子类create
方法中的do
方法调用。有办法解决这个问题吗?
在B.create
上添加类型提示似乎可以做到这一点,即使有mypy启用的严格选项
from typing import Type, TypeVar
T = TypeVar('T', bound='A')
U = TypeVar('U', bound='B')
class A:
@classmethod
def create(cls: Type[T]) -> T:
return cls()
class B(A):
def do(self) -> None:
pass
@classmethod
def create(cls: Type[U]) -> U:
obj = super().create()
obj.do()
return obj
if __name__ == '__main__':
b = B.create()