簡體   English   中英

Python 3.1 中鴨子打字的最小訂購方法

[英]Minimum Methods for Ordering with Duck Typing in Python 3.1

手冊中說:

通常,如果您想要比較運算符的常規含義,__ __lt__()__eq__()就足夠了

但我看到錯誤:

>       assert 2 < three
E       TypeError: unorderable types: int() < IntVar()

當我運行這個測試時:

from unittest import TestCase

class IntVar(object):

    def __init__(self, value=None):
        if value is not None: value = int(value)
        self.value = value

    def __int__(self):
        return self.value

    def __lt__(self, other):
        return self.value < other

    def __eq__(self, other):
        return self.value == other

    def __hash__(self):
        return hash(self.value)

class DynamicTest(TestCase):

    def test_lt(self):
        three = IntVar(3)
        assert three < 4
        assert 2 < three
        assert 3 == three

我很驚訝當IntVar()在右邊時, __int__()沒有被調用。 我究竟做錯了什么?

添加__gt__()解決了這個問題,但這意味着我不明白訂購的最低要求是什么......

謝謝,安德魯

Python 3.x 永遠不會對運算符進行任何類型強制轉換,因此在此上下文中不使用__int__() 比較

a < b

將首先嘗試調用type(a).__lt__(a, b) ,如果返回NotImplemented ,它將調用type(b).__gt__(b, a)

文檔中的引述是關於對單一類型進行比較,上面的解釋說明了為什么這對單一類型就足夠了。

要使您的類型與int正確交互,您應該實現所有比較運算符,或者使用 Python 2.7 或 3.2 中提供的total_ordering裝飾器

暫無
暫無

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

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