下面的代码首先定义协议Proto
,然后定义一个函数,该函数接受遵循该协议的变量.然后定义类A
和B
,我认为它们都遵循协议,尽管只有参数名B.__call__
与协议不同(在Proto
中是x
,在B
中是y
).
在使用mypy判断以下代码后,出现以下错误
main.py:20: error: Argument 1 to "func" has incompatible type "B"; expected "Proto"
似乎,协议不仅强制类型,而且还强制参数名称.这是故意的行为吗?或者是Mypy出了什么问题?
from typing import Protocol
class Proto(Protocol):
def __call__(self, x: int) -> int:
...
def func(f: Proto):
pass
class A:
def __call__(self, x: int) -> int:
return x
class B:
def __call__(self, y: int) -> int:
return y
func(A())
func(B())