已解決:Python __sub__ 魔術方法

Python 中的 __sub__ 魔術方法用於調用帶有兩個參數的函數,但第一個參數被解釋為第二個參數類的子類。 如果子類沒有實現 __sub__ 魔術方法,這可能會導致意外行為。

The __sub__ magic method is used to implement the subtraction operator for objects. It is called when the - operator is used on two objects of the same type. The __sub__ method should return the result of the subtraction operation.

For example, if we have a class that represents a complex number, we could define the __sub__ method like this:

class ComplexNumber: def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def __sub__(self, other): return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)

Now we can use the - operator on two ComplexNumber objects:

c1 = ComplexNumber(1, 2) c2 = ComplexNumber(3, 4) c3 = c1 - c2 print(c3) # Prints ComplexNumber(real=-2, imaginary=-2)

什麼是魔術方法

在 Python 中,魔術方法是一種特殊類型的函數,它允許您在不指定函數名稱的情況下調用函數。 這是通過在函數名稱前加上一個符號 (&) 來完成的。

魔術方法列表

有許多不同的方法可以在 Python 中施展魔法。 這裡有一些:

1.導​​入隨機
2.導入時間
3. 從數學導入 sqrt, pi
4. from datetime 導入日期、時間
5. from operator import 加減乘除
6.從函數導入部分
7.從集合導入雙端隊列

相關文章:

發表評論