考虑一个也用协议注释的Python协议属性.我发现在这种情况下,即使我的定制数据类型遵循嵌套协议,mypy和Pyright也会报告错误.例如,在下面的代码中,Outer
遵循HasHasA
协议,因为它有hasa: HasA
,因为Inner
遵循HasA
协议.
from dataclasses import dataclass
from typing import Protocol
class HasA(Protocol):
a: int
class HasHasA(Protocol):
hasa: HasA
@dataclass
class Inner:
a: int
@dataclass
class Outer:
hasa: Inner
def func(b: HasHasA): ...
o = Outer(Inner(0))
func(o)
但是,mypy显示以下错误.
nested_protocol.py:22: error: Argument 1 to "func" has incompatible type "Outer"; expected "HasHasA" [arg-type]
nested_protocol.py:22: note: Following member(s) of "Outer" have conflicts:
nested_protocol.py:22: note: hasa: expected "HasA", got "Inner"
我的代码有什么问题?