我有一個指定position成員的介面。因為我希望它對成員是作為一個@property屬性還是一個直接屬性實作不可知,所以我將型別注釋為兩者的聯合
class Moveable(Protocol):
position: property or Tuple[int, int]
entity: Moveable = Player() # Player implements `.position` as a getter
這行得通。但是,切換型別會導致 Pylance 錯誤。
class Moveable(Protocol):
position: Tuple[int, int] or property
(class) Player()
Expression of type "Player" cannot be assigned to declared type "Moveable"
"Player" is incompatible with protocol "Moveable"
"position" is invariant because it is mutable
"position" is an incompatible type
"property" is incompatible with "Tuple[int, int]"PylancereportGeneralTypeIssues
我不明白為什么順序很重要,因為(P or Q) <-> (Q or P). 這違反了交換律
uj5u.com熱心網友回復:
代替or,使用Union[]或|
https://docs.python.org/3/library/typing.html#typing.Union
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532944.html
