mypy 不会警告实例化纯虚拟 class

mypy doesn't warn about instantiating pure virtual class

我有一个抽象 class 指定了一个纯虚方法 run:

class Father:
    def __init__(self):
        self.i = 800
    def run(self, s: str) -> int:
        pass

class Son(Father):
    def walk(self, i: int) -> int:
        return self.i+i+800

s = Son()

当我运行mypy没有发出警告,为什么?

您的示例没有抽象 class 或纯虚方法(严格来说,这不是 Python 中的内容;它只是一个抽象方法) .它在层次结构中有两个标准的classes,run函数是一个常规函数。

如果你想要一个抽象方法,你必须这样标记它using the bits and bobs in the abc module

from abc import ABC, abstractmethod


class Father(ABC):
    def __init__(self):
        self.i = 800

    @abstractmethod
    def run(self, s: str) -> int:
        ...


class Son(Father):
    def walk(self, i: int) -> int:
        return self.i + i + 800


s = Son()

这导致

TypeError: Can't instantiate abstract class Son with abstract method run

在运行时和

error: Cannot instantiate abstract class "Son" with abstract attribute "run"

在 mypy 的时候。

如果您不关心运行时检查,请不要从 ABC 派生 Father