Python - AI 助手

Python functools.total_ordering() 函式



Python 的 **functools.total_ordering()** 函式裝飾器來自 functools 模組,簡化了所有比較方法的實現。functools 模組旨在指定高階函式,而 total_ordering 裝飾器就是一個典型的例子。它增強了類的功能,而無需為每個比較方法進行顯式定義,使程式碼更易於維護和高效。

語法

以下是 **total_ordering()** 函式的語法。

@total_ordering()

引數

此函式不接受任何引數。

返回值

裝飾器返回具有其他比較方法(如 (__le__, __gt__, __ge__) 的類。以下示例演示了

示例 1

下面的示例演示了一個類,其中包含 __le__、__gt__ 和 __ge__ 等方法,這些方法由 **total_ordering** 裝飾器自動提供。

from functools import total_ordering
@total_ordering
class Num:
    def __init__(self, val):
        self.val = val

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

    def __lt__(self, other):
        return self.val < other.val
print(Num(31) < Num(12)) 
print(Num(200) > Num(101)) 
print(Num(56) == Num(18))
print(Num(2) != Num(2)) 

輸出

結果如下生成:

False
True
False
False

示例 2

在此示例中,total_ordering() 裝飾器根據單詞文字的長度比較單詞物件。透過定義 __eq__ 和 __lt__ 方法,它會自動提供其他比較方法,從而簡化比較邏輯。

from functools import total_ordering
@total_ordering
class Word:
    def __init__(self, txt):
        self.txt = txt

    def __eq__(self, other):
        return len(self.txt) == len(other.txt)

    def __lt__(self, other):
        return len(self.txt) < len(other.txt)
print(Word("grapes") < Word("watermelon"))  
print(Word("banana") < Word("kiwi"))     
print(Word("pineapple") == Word("grape")) 

輸出

程式碼如下生成:

True
False
False

示例 3

我們現在正在建立一個程式碼,該程式碼定義了一個具有 n 和 p 座標的點類。使用 **total_ordering()** 函式裝飾器,簡化了程式碼,方法是定義 __eq__ 和 __lt__ 方法。裝飾器允許根據點的座標輕鬆比較點物件。

from functools import total_ordering
@total_ordering
class Point:
    def __init__(self, n, p):
        self.n = n
        self.p = p

    def __eq__(self, other):
        return (self.n, self.p) == (other.n, other.p)

    def __lt__(self, other):
        return (self.n, self.p) < (other.n, other.p)
print(Point(31, 4) < Point(21, 11)) 
print(Point(10, 12) > Point(0, 13)) 
print(Point(2, 2) == Point(1, 1))

輸出

輸出如下獲得:

False
True
False
python_modules.htm
廣告