在 Python 中,運算子是如何對映到魔法方法的?


在本文中,我們將向您解釋 Python 中的運算子是如何對映到魔法方法的。

Python 的魔法方法是特殊的方法,它們以雙下劃線開頭和結尾。它們也被稱為dunder方法。魔法方法不打算由您直接呼叫,而是由類在特定操作時呼叫。當您使用 + 運算子將兩個數字相加時,__add__() 方法會在內部被呼叫。

Python 中的許多魔法方法都是由內建類定義的。要獲取類繼承的魔法方法的數量,請使用dir() 函式。

示例

以下程式列出了在int 類中定義的所有屬性和方法。

print(dir(int))

輸出

執行後,以上程式將生成以下輸出:

['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', 
'__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__',
'__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', 
'__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', 
'__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', 
'__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', 
'__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', 
'__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', 
'__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', 
'__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 
'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

這裡,int 類包含許多用雙下劃線包圍的魔法方法。

__add__ 方法

__add__ 方法是當我們使用+ 運算子將兩個值相加時呼叫的魔法方法。1. 在 Python 中,運算子是如何對映到魔法方法的?

示例

以下程式使用魔法方法的__add__ 方法運算子返回給定值與一個值的和:

n = 20 # adding 10 to input number using + sign print("Addition using + sign:", n + 10) # adding 10 to input number using __add__ method # by passing the value to be added as an argument print("Addition using __add__ method:", n.__add__(10))

輸出

執行後,以上程式將生成以下輸出:

Addition using + sign: 30
Addition using __add__ method: 30

正如您所看到的,當您輸入 n+10 時,+ 運算子會呼叫__add__(10) 方法。您也可以顯式地呼叫n.__add__(10) 來獲得相同的結果。但是,如前所述,魔法方法並非旨在直接呼叫,而是透過其他方法或操作間接呼叫。

在 Python 中,魔法方法最常用於定義預定義運算子的過載行為。例如,算術運算子預設情況下對數字運算元進行運算。這意味著必須將數字物件與諸如 +、-、*、/ 等運算子結合使用。在字串、列表和元組類中,+ 運算子也被指定為連線運算子。+ 運算子被稱為過載。

要在您自己的自定義類中使用過載行為,請覆蓋相應的魔法方法。例如,要將 + 運算子與使用者定義類的物件一起使用,它必須包含__add__() 方法。

__new__() 方法

要建立類的新的例項,Java 和 C# 等語言使用 new 運算子。在 Python 中,__new__() 魔法方法在__init__() 方法之前隱式呼叫。__new__() 方法返回一個新物件,隨後使用__init__() 方法對其進行初始化。

示例

# defining a class class Tutorialspoint: def __new__(democlass): print ("calling __new__ magic method") instance = object.__new__(democlass) return instance def __init__(self): print ("calling __init__ magic method") self.author ='XYZ' # calling the above-defined Tutorialspoint class result = Tutorialspoint()

輸出

執行後,以上程式將生成以下輸出:

calling __new__ magic method
calling __init__ magic method

在這裡,當您建立Tutorialspoint 類的例項時,您將獲得上述結果。

因此,__new__() 方法在__init__() 方法之前呼叫。

__str__() 方法

__str__() 是另一個重要的魔法方法。它被重寫以返回任何使用者定義類的可列印字串表示形式。我們已經看到了內建函式str(),它從作為引數傳遞的物件返回一個字串。

示例

# input number n = 10 # printing the string form of a number using str() print(str(n)) # printing the string form of a number using __str__() magic method # Both are equivalent print(int.__str__(n))

輸出

執行後,以上程式將生成以下輸出:

10
10

這裡,str(10) 返回值“10”。當被呼叫時,它會呼叫 int 類的__str__() 方法。

並且str() 函式在內部呼叫在類中定義的__str__() 方法。因此,它被稱為魔法方法!

重要的魔法方法

下表列出了 Python 3 中最重要的魔法方法。

初始化和構造 描述
__new__(cls, other) 在物件例項化時呼叫。
__init__(self, other) 由 __new__ 方法呼叫。
__del__(self) 析構方法。
一元運算子和函式 描述
__pos__(self) 對一元正數呼叫,例如:+someobject。
__neg__(self) 對一元負數呼叫,例如:-someobject。
__abs__(self) 由內建 abs() 函式呼叫。
__invert__(self) 使用 ~ 運算子進行反轉時呼叫。
__round__(self,n) 由內建 round() 函式呼叫。
__floor__(self) 由內建 math.floor() 函式呼叫。
__ceil__(self) 由內建 math.ceil() 函式呼叫。
__trunc__(self) 由內建 math.trunc() 函式呼叫。
增強賦值 描述
__iadd__(self, other) 在帶賦值的加法運算中呼叫,例如:a +=b。
__isub__(self, other) 在帶賦值的減法運算中呼叫,例如:a -=b。
__imul__(self, other) 在帶賦值的乘法運算中呼叫,例如:a *=b。
__ifloordiv__(self, other) 在帶賦值的整數除法運算中呼叫,例如:a //=b。
__idiv__(self, other) 在帶賦值的除法運算中呼叫,例如:a /=b。
__itruediv__(self, other) 在帶賦值的真除法運算中呼叫
__imod__(self, other) 在帶賦值的取模運算中呼叫,例如:a%=b。
__ipow__(self, other) 在帶賦值的冪運算中呼叫,例如:a **=b。
__ilshift__(self, other) 在帶賦值的左移位運算中呼叫,例如:a<<=b。
__irshift__(self, other) 在帶賦值的右移位運算中呼叫,例如:a >>=b。
__iand__(self, other) 在帶賦值的按位與運算中呼叫,例如:a&=b。
__ior__(self, other) 在帶賦值的按位或運算中呼叫,例如:a|=b。
__ixor__(self, other) 在帶賦值的按位異或運算中呼叫,例如:a ^=b。

類似地,我們還有許多其他魔法方法,例如型別轉換魔法方法、字串魔法方法、屬性魔法方法、運算子魔法方法等 - 連結

結論

在本文中,我們透過示例瞭解了一些對映到魔法方法的運算子。在本文中,我們學習了魔法方法及其使用方法,以及魔法方法的一些運算子。

更新於:2022年11月9日

350 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告