[英]mypy generic subclass leads to incompatible types
我正在玩弄带有类型提示的幺半群。 为此,我写道:
M = TypeVar('M')
class Monoid(Generic[M]):
...
def append(self, m: 'Monoid[M]') -> 'Monoid[M]':
raise NotImplementedError()
在子类中使用 this 时,例如
A = TypeVar('A')
class List(Monoid[A], Generic[A]):
def __init__(self, *values: A) -> None:
self._values = tuple(values)
...
def append(self, m: 'List[A]') -> 'List[A]':
return List(*(self.values + m.values))
我收到error: Argument 1 of "append" incompatible with supertype "Monoid"
。 由于List
是Monoid
的适当子类,我希望它能够输入。 我究竟做错了什么?
好吧,您的List
类不是Monoid 的正确子类型。 毕竟,您说过所有 Monoid 都必须有一个 append 方法,可以接受任意 Monoid 或 Monoid 的子类——那么,为什么可以缩小 List 的范围,使其append
只能接受特定的 List?
这违反了Liskov 替换原则。
您可以使用通用 self解决此特定情况:
M = TypeVar('M')
T = TypeVar('T')
class Monoid(Generic[M]):
...
def append(self: T, m: T) -> T:
raise NotImplementedError()
现在,您表示Monoid
所有子类都必须实现一个append
方法,该方法专门接受该子类的类型。 有了这个新版本的 Monoid,你的 List 类现在是类型安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.