键入:更改 python 中继承的 class 中的字段类型

Typing: changing type of fieldin inherited class in python

让我们采取:

class A:
    pass

class A2(A):
    @property
    def f(self):
        return None

class B:
    def __init__(el: A)
        self._a = el

class B2(B):
    def __init__(el: A2)
        super().__init__(el)

    def m():
        self._a.f()

我现在在调用 self._a.f() 时在最后一行出现输入错误,说“无法访问类型 A 的成员 f”,即使它是在 B 中的 A2 处声明的,并且它有成员。 声明此代码段以使其正常工作的正确方法是什么?

A 没有成员 f,因此尝试访问 _a.f,其中 _a: A 是错误的。为了实现你想要的,你应该将 f 定义为 A 上的一个未实现的函数,它的子类应该实现:

class A:
    @property
    def f(self):
        raise NotImplementedError

或者使用抽象方法使其成为 abstract base class:

from abc import ABC, abstractmethod

class A(ABC):
    @property
    @abstractmethod
    def f(self): ...

这将通知类型检查器 A 及其所有子类都有一个成员 f,并且您的代码应该正确地进行类型检查。

如果你只想缩小 B2._a 的类型,这应该足够了:

class B2(B):
    _a: A2

    # rest of class definition
    ...