简体   繁体   English

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

[英]Python + mypy + mixin = has no attribute error

I have Vscode + mypy error in the UI interface: "EngineMixin" has no attribute "engine" for the next Mixin class我在UI界面出现Vscode + mypy错误:“EngineMixin” has no attribute “engine” for next Mixin class

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

In fact, this error is shown only in Vscode UI interface.实际上,这个错误只在 Vscode UI 界面中显示。 When I run mypy in cli, there are no errors.当我在 cli 中运行 mypy 时,没有错误。 In general, I understand why this error appears, but is there any way to supress it in vscode?总的来说,我理解为什么会出现这个错误,但是有没有办法在 vscode 中抑制它?

Edited (added screen):编辑(添加屏幕): 截屏

For mixins that refer to the class they're being mixed into, you can use a type stub to let mypy know that self.engine is expected to exist对于引用 class 的 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM