Код: Выделить всё
# my_list.py
from __future__ import annotations
class MyList(list[int]):
def __add__(self, other: list[int]) -> MyList:
return MyList()
Код: Выделить всё
> mypy .\my_list.py --strict
my_list.py:5: error: Signature of "__add__" incompatible with supertype "list" [override]
my_list.py:5: note: Superclass:
my_list.py:5: note: @overload
my_list.py:5: note: def __add__(self, list[int], /) -> list[int]
my_list.py:5: note: @overload
my_list.py:5: note: def [_S] __add__(self, list[_S], /) -> list[_S | int]
my_list.py:5: note: Subclass:
my_list.py:5: note: def __add__(self, list[int], /) -> MyList
Код: Выделить всё
from typing import overload, TypeVar
_T = TypeVar("_T")
class MyList(list[int]):
@overload
def __add__(self, other: list[int]) -> list[int]:
...
@overload
def __add__(self, other: list[_T]) -> list[_T | int]:
...
def __add__(self, other: list[_T] | list[int]) -> list[_T | int]:
return [0]
Кроме того, проблема усугубляется, если мы попытаемся добавить метод __iadd__... Тогда он либо скажет, что его сигнатура несовместима с сигнатурой __add__, либо несовместима с подпись какого-то суперкласса...
Код: Выделить всё
Signature of "__iadd__" incompatible with "__add__" of supertype "list" [override]
Signatures of "__iadd__" and "__add__" are incompatible [misc]
Подробнее здесь: https://stackoverflow.com/questions/792 ... ss-of-list
Мобильная версия