Как решить проблему «Несовместимый тип возвращаемого значения (получено «FancyCat», ожидается «Self»)»Python

Программы на Python
Anonymous
Как решить проблему «Несовместимый тип возвращаемого значения (получено «FancyCat», ожидается «Self»)»

Сообщение Anonymous »

Вот минимальный пример, который я написал:

Код: Выделить всё

from __future__ import annotations

from typing import Protocol
from typing_extensions import Self

class Cat(Protocol):
def add(self, other: Self) -> Self:
...
def sub(self, other: Self) -> Self:
...

class FancyCat(Cat):
def __init__(self, value: int):
self._value = value

def add(self, other: Self) -> Self:
return FancyCat(self._value + other._value)

def sub(self, other: Self) -> Self:
return FancyCat(self._value - other._value)

fc = FancyCat(3)
fc2 = FancyCat(4)
fc.add(fc2)
Если я попытаюсь ввести проверку, я получу

Код: Выделить всё

$ mypy t.py
t.py:19: error: Incompatible return value type (got "FancyCat", expected "Self")  [return-value]
t.py:22: error: Incompatible return value type (got "FancyCat", expected "Self")  [return-value]
Found 2 errors in 1 file (checked 1 source file)
Я в таком замешательстве – разве в данном случае не Self FancyCat?
Как я могу удовлетворить mypy здесь?

Подробнее здесь: https://stackoverflow.com/questions/773 ... ected-self

Вернуться в «Python»