[英]How to annotate `__eq__` when it uses an attribute?
給定以下課程,我應該如何注釋__eq__
?
class Foo(object):
def __init__(self, bar):
self.bar = bar
def __eq__(self, other):
return Foo.bar == other.bar
使用__eq__(self, other: Foo) -> bool
使mypy
錯誤:
Argument 1 of "__eq__" is incompatible with supertype "object"; supertype defines the argument type as "object"
並使用__eq__(self, other: object) -> bool
使mypy
錯誤:
"object" has no attribute "bar"
我該怎么辦?
建議__eq__
與任意對象一起使用。 在此示例中,您需要首先確保other
是Foo
類的成員:
def __eq__(self, other: object) -> bool:
if not isinstance(other, Foo):
return NotImplemented
return Foo.bar == other.bar
object.__eq__()
必須處理任何類型的對象,而不僅僅是您自己的類。 對於不需要處理的類型,返回NotImplemented
,因此Python可以詢問右側操作數是否要處理相等性測試。
根據Python格式化指南將other
參數注釋為object
:
def __eq__(self, other: object) -> bool:
if not isinstance(other, Foo):
return NotImplemented
return Foo.bar == other.bar
將other
設置為object
實際上告訴類型檢查器可以接受任何從object
繼承的東西(在Python中是一切 )。 isinstance(other, Foo)
測試告訴類型檢查器,使它到達函數最后一行的任何對象不僅是object
的實例,而且還具體是Foo
或其他子類的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.