Mypy报错:实现IState接口的子类与接口类型赋值不兼容
解决mypy类型不兼容错误:IState赋值给AguardandoPagamentoState类型变量
你的代码运行正常,但mypy静态类型检查时抛出如下错误:
Incompatible types in assignment (expression has type "IState", variable has type "AguardandoPagamentoState") [assignment]mypy
错误原因
mypy会根据变量的初始赋值自动推断类型。在Pedido类的__init__方法中,你给self.estado_atual赋值了AguardandoPagamentoState(self),因此mypy将这个变量的类型推断为具体子类AguardandoPagamentoState,而非它实现的父接口IState。但set_estado_atual方法接收的参数类型是IState,当你通过该方法给self.estado_atual赋值其他IState子类(比如PagoState、CanceladoState)时,就会触发类型不兼容报错——mypy认为该变量只能接收AguardandoPagamentoState类型实例,而你要赋值的是更宽泛的IState类型。
解决方法
给Pedido类的estado_atual属性显式标注类型为IState,明确告诉mypy这个变量可以接受任何实现了IState接口的子类实例。修改后的Pedido类代码如下:
class Pedido: """Classe que representa um pedido.""" estado_atual: IState # 显式声明属性类型 def __init__(self) -> None: self.estado_atual = AguardandoPagamentoState(self) def realizar_pagamento(self) -> None: self.estado_atual.sucesso_ao_pagar() def despachar(self) -> None: self.estado_atual.despachar_pedido() def cancelar(self) -> None: self.estado_atual.cancelar_pedido() def set_estado_atual(self, estado_atual: IState) -> None: self.estado_atual = estado_atual def __str__(self) -> str: return str(self.estado_atual)
添加显式类型标注后,mypy就能正确识别变量的类型范围,不会再抛出赋值不兼容的错误。
内容的提问来源于stack exchange,提问作者Magaren
相关产品推荐
相关产品推荐

