(相关,但不重复:How to annotate that can be implemented as property?)
我想创建一个Protocol
,其中一个字段可以通过简单的类型和属性来实现。例如:
class P(Protocol):
v: int
@dataclass
class Foo(P):
v: int
class Bar(P):
@property
def v(self) -> int: # ERROR
return
但是上面的代码没有类型检查。我应该如何解决它?
注意:我想在不重写Foo
and的情况下解决这个问题Bar
,因为Foo
andBar
不是我实现的。
根据这个问题,下面的代码不是解决方案,因为只读property
和简单成员的语义略有不同。
class P(Protocol):
@property
def v(self) -> int: # declare as property
...
Protocol
由于差异,Pyright 否认了这一点。