如何在子类化时不必在 init 中键入 self

How to not have to type self in init when subclassing

MCVE:

class A:
    def __init__(self, num: int):
        self.value = num

class B(A):
    def __init__(self): # Mypy: function is missing a type annotation
        A.__init__(self, 7) # Mypy: Expression has type "Any"

我希望 Mypy 不要强迫我必须输入 selfself 的类型对我来说似乎很明显,而且 Mypy 能够为 A 计算出来,所以为什么不 B

如何定义 B 以便我不会被迫执行以下操作?

class A:
    def __init__(self, num: int):
        self.value = num

class B(A):
    def __init__(self: 'B'):
        A.__init__(self, 7)

您需要在签名中注明 return 类型:

class Foo:
    def __init__(self) -> None:
        pass

如果注释了一个或多个其他参数,Mypy 将允许您在特定构造函数上省略 return 类型,但您需要将其包含在 no-argument 构造函数中。