Python + mypy + mixin = 没有属性错误

问题描述

我在 UI 界面中有 Vscode + mypy 错误:“EngineMixin”没有属性“engine” 为下一个 Mixin 课程

class EngineMixin:
    def prepare_start(self):
        self.engine.start()

    def prepare_stop(self):
        self.engine.stop()

    def __str__(self):
        output = super().__str__()
        output += f'\n{self.__class__.__name__} characteristics. Engine [{self.engine}]' # noqa
        return output

其实这个错误只出现在Vscode UI界面。当我在 cli 中运行 mypy 时,没有错误。 总的来说,我明白为什么会出现这个错误,但是有没有办法在 vscode 中抑制它?

已编辑(添加屏幕):

screenshot

解决方法

对于引用它们被混入的类的 mixin,您可以使用类型存根让 mypy 知道 self.engine 预计存在

class EngineMixin:

    # Like this
    engine: Engine

    def prepare_start(self):
        self.engine.start()

    def prepare_stop(self):
        self.engine.stop()

    def __str__(self):
        output = super().__str__()
        output += f'\n{self.__class__.__name__} characteristics. Engine [{self.engine}]' # noqa
        return output

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...