这是我写的一个最小的例子:
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
?
您的代码不保证 Self 会被返回。例如,子类仍然会返回
FancyCat
,因此Self
注释无效。
要消除错误,您可以:
a) 确保始终返回
self.__class__
,这是实际的 Self
def add(self, other: Self) -> Self:
return self.__class__(self._value + other._value)
b)输入您实际返回的内容,
FancyCat
def sub(self, other: Self) -> FancyCat:
return FancyCat(self._value - other._value)