在 Python 中,許多運算符都可以進行重載,以下是一些常見運算符及其對應的魔法方法(特殊方法):
算術運算符
- 加法
+
:__add__
用于定義對象相加的行為。例如,當你對兩個自定義類的實例使用+
運算符時,會調用__add__
方法。
class MyNumber:def __init__(self, value):self.value = valuedef __add__(self, other):return MyNumber(self.value + other.value)num1 = MyNumber(5)
num2 = MyNumber(3)
result = num1 + num2
print(result.value)
- 減法
-
:__sub__
你已經了解到它可以用于計算兩個對象之間的差值。 - 在 Python 里,減法運算符
-
的重載并非 Python 庫自帶的功能,而是 Python 面向對象編程里的一種特性,名為運算符重載。下面詳細給你解釋這一概念。
運算符重載的概念
運算符重載允許你為自定義類重新定義運算符的行為。比如,在 Python 中,你可以為自定義類定義 __sub__
方法,這樣在使用 -
運算符對該類的實例進行操作時,就會調用你定義的 __sub__
方法。
__sub__
方法示例
在你的 Cube
類里,__sub__
方法的定義如下:
def __sub__(self, other):return (self.x - other.x, self.y - other.y)
這里的 self
代表運算符 -
左邊的 Cube
實例,other
代表運算符 -
右邊的 Cube
實例。該方法返回一個元組,包含兩個 Cube
實例在 x
和 y
方向上的坐標差值。
示例代碼說明
以下是一個簡單的示例,展示了如何使用 __sub__
方法:
import numpy as np# 假設 SIZE 已經定義
SIZE = 10class Cube:def __init__(self):self.x = np.random.randint(0, SIZE)self.y = np.random.randint(0, SIZE)def __str__(self):return f'{self.x}, {self.y}'def __sub__(self, other):return (self.x - other.x, self.y - other.y)def action(self, choise):if choise == 0:self.move(x=1, y=1)elif choise == 1:self.move(x=-1, y=1)elif choise == 2:self.move(x=1, y=-1)elif choise == 3:self.move(x=-1, y=-1)def move(self, x=False, y=False):if not x:self.x += np.random.randint(-1, 2)else:self.x += xif not y:self.y += np.random.randint(-1, 2)else:self.y += yif self.x < 0:self.x = 0elif self.x >= SIZE - 1:self.x = SIZE - 1if self.y < 0:self.y = 0elif self.y >= SIZE - 1:self.y = SIZE - 1# 創建兩個 Cube 實例
cube1 = Cube()
cube2 = Cube()# 打印兩個 Cube 實例的位置
print(f"Cube 1 的位置: {cube1}")
print(f"Cube 2 的位置: {cube2}")# 使用減法運算符計算兩個 Cube 實例之間的相對位置
relative_position = cube1 - cube2
print(f"Cube 1 相對于 Cube 2 的位置: {relative_position}")
在這個示例中,我們創建了兩個 Cube
實例 cube1
和 cube2
,接著使用 -
運算符計算它們之間的相對位置。由于我們在 Cube
類中定義了 __sub__
方法,所以 -
運算符會調用該方法并返回兩個 Cube
實例在 x
和 y
方向上的坐標差值。
總結
__sub__
方法是 Python 運算符重載的一種應用,它允許你為自定義類重新定義減法運算符 -
的行為。通過定義 __sub__
方法,你可以方便地計算兩個 Cube
實例之間的相對位置。
- 乘法
*
:__mul__
定義對象相乘的行為。
class MyNumber:def __init__(self, value):self.value = valuedef __mul__(self, other):return MyNumber(self.value * other.value)num1 = MyNumber(5)
num2 = MyNumber(3)
result = num1 * num2
print(result.value)
- 除法
/
:__truediv__
用于實現真除法。
class MyNumber:def __init__(self, value):self.value = valuedef __truediv__(self, other):return MyNumber(self.value / other.value)num1 = MyNumber(6)
num2 = MyNumber(3)
result = num1 / num2
print(result.value)
- 取模
%
:__mod__
定義取模運算的行為。 - 冪運算
**
:__pow__
實現冪運算。
比較運算符
- 等于
==
:__eq__
用于判斷兩個對象是否相等。
class MyNumber:def __init__(self, value):self.value = valuedef __eq__(self, other):return self.value == other.valuenum1 = MyNumber(5)
num2 = MyNumber(5)
print(num1 == num2)
- 不等于
!=
:__ne__
定義不等于的比較邏輯。 - 小于
<
:__lt__
用于判斷一個對象是否小于另一個對象。 - 小于等于
<=
:__le__
實現小于等于的比較。 - 大于
>
:__gt__
定義大于的比較行為。 - 大于等于
>=
:__ge__
實現大于等于的比較。
賦值運算符
- 加法賦值
+=
:__iadd__
用于定義對象相加并賦值的行為。
class MyNumber:def __init__(self, value):self.value = valuedef __iadd__(self, other):self.value += other.valuereturn selfnum1 = MyNumber(5)
num2 = MyNumber(3)
num1 += num2
print(num1.value)
- 減法賦值
-=
:__isub__
- 乘法賦值
*=
:__imul__
- 除法賦值
/=
:__itruediv__
位運算符
- 按位與
&
:__and__
定義按位與的行為。 - 按位或
|
:__or__
實現按位或的運算。 - 按位異或
^
:__xor__
定義按位異或的邏輯。 - 按位取反
~
:__invert__
- 左移
<<
:__lshift__
- 右移
>>
:__rshift__
其他運算符
- 索引訪問
[]
:__getitem__
和__setitem__
分別用于獲取和設置對象的索引元素。
class MyList:def __init__(self):self.data = [1, 2, 3]def __getitem__(self, index):return self.data[index]def __setitem__(self, index, value):self.data[index] = valuemy_list = MyList()
print(my_list[0])
my_list[0] = 10
print(my_list[0])
- 調用對象
()
:__call__
允許將對象像函數一樣調用。
class Adder:def __call__(self, a, b):return a + badder = Adder()
result = adder(3, 5)
print(result)
通過重載這些運算符,你可以讓自定義類的對象像內置類型一樣進行各種操作,增強代碼的可讀性和可維護性。