在Python3中,如何让键入系统知道由"super().*"方法创建的子类实例具有子类方法


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()

相关内容