← 從零開始學 Python 第 66 課,共 78 課 · 10 XP

特殊方法

理論與題目說明

機器翻譯,尚未經母語人士審閱。

用兩個底線包起來的方法(__init__、__str__…)叫做特殊方法或「dunder」方法。使用一般的語法時,Python 會自動呼叫它們:

這樣寫時 Python 呼叫的是
str(v)、print(v) v.__str__()
互動式介面裡的 v、在串列裡 v.__repr__()
a + b a.__add__(b)
a == b a.__eq__(b)
len(v) v.__len__()
a < b a.__lt__(b)

有了它們,自己的物件就能像內建型別一樣運作:

class Money:
    def __init__(self, amount):
        self.amount = amount

    def __add__(self, other):
        return Money(self.amount + other.amount)

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

    def __str__(self):
        return f"NT${self.amount}"

print(Money(100) + Money(50))    # NT$150

沒有 __eq__ 的話,資料相同的兩個物件也不會相等:預設的 == 檢查的是不是同一個物件。

題目。 建立有座標 x、y 的類別 Vector。用 + 相加兩個向量時得到新的向量,== 比較座標,str() 回傳 (x, y)。

免費註冊,就能直接在瀏覽器裡解這道題:程式碼編輯器、執行、測試檢查和提示。