Python 3 base class type annotation 只允许当前子class

Python 3 base class type annotation only allow the current subclass

假设我有三个 classes,一个父 class 和两个子 classes:

class BaseModel:
    def merge(self, other):
        return self + other

class ChildA(BaseModel):
    pass

class ChildB(BaseModel):
    pass

父 class 有一个方法获取当前 class 的另一个实例和 returns 当前 class 的一个新实例(超出此范围)问题)。

如何注释 BaseModel.merge 以将其限制为仅当前子class?

我可以这样做:

def merge(self, other: BaseModel) -> BaseModel:
    return self + other

但这仍然允许我将 ChildB 的实例传递给 ChildA,因为它们都继承自 BaseModel。我只希望在 ChildA 中允许 ChildA,并且在 ChildB 中允许 ChildB。如果不在每个子 class 上重新实现 merge,我该怎么做?

用类型变量注释两个 参数,以强制两个参数必须是同一类型。

from typing import TypeVar

B = TypeVar('B', bound='BaseModel')

class BaseModel:
    def __init__(self, x: int):
        self.x = x

    def __add__(self: B, other: B) -> B:
        return type(self)(self.x + other.x)

    def merge(self: B, other: B) -> B:
        return self + other

class ChildA(BaseModel):
    pass

class ChildB(BaseModel):
    pass


print(ChildA(3).merge(ChildA(4)).x)  # Valid; both arguments are ChildA      
print(ChildA(3).merge(ChildB(4)).x)  # Invalid; one ChildA and one ChildB