簡體   English   中英

使用屬性時如何注釋__eq__?

[英]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__與任意對象一起使用。 在此示例中,您需要首先確保otherFoo類的成員:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM