簡體   English   中英

Python運算符重載查詢

[英]Python operator overloading query

假設我們定義x = C(['0']) ,其中類C定義為

class C:
    def __init__(self,los):
        self.los = los

    def __lt__(self,right):
        if type(right) is C:
            return self.los < right.los
        elif type(right) is int:
            return self.los < [d for d in str(right)]
        else:
            raise TypeError('unorderable types: C() < '+type_as_str(right)+'()')

x = C(['0'])
print(12<x)

執行以上代碼后,它將返回“ False”。 如果我的理解很好,那么對於12<x ,它將是12.__lt__(x) ,除了type(12).__lt__(12, x)int.__lt__(12, x) 因此,它將嘗試在標准int類中使用__lt__方法。 但是它應該拋出錯誤消息,因為此方法不了解int與類對象的比較。 因此,將在內部管理此異常,然后應調用x.__lt__(12)type(x).__lt__(x, 12) 這意味着最后它應該使用在類C中定義的__lt__方法。

但是似乎沒有調用該類,因為我試圖在C類的__lt__方法中放置一些打印內容,並且print(12<x)始終返回False

有人可以詳細解釋一下嗎?

您是正確的int.__lt__(12, x)將不起作用; 在這種情況下,該方法返回NotImplemented單例:

>>> int.__lt__(12, x)
NotImplemented

但是,Python然后調用type(x).__gt__()而不是__lt__

>>> class Demo:
...     def __lt__(self, other):
...         print('__lt__ called')
...         return NotImplemented
...     def __gt__(self, other):
...         print('__gt__ called')
...         return NotImplemented
...
>>> 12 < Demo()
__gt__ called
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < Demo()

那是因為您仍然可以通過詢問另一個對象是否大於12來確定12是否小於另一個對象。 如果您要求取反數( 12 > x ), 您的C.__lt__()稱為:

>>> 12 > Demo()
__lt__ called
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() > Demo()

需要注意的是Python的引發TypeError異常,因為Demo.__gt__()Demo.__lt__()都返回NotImplemented 您不必自己提出異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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