政府網(wǎng)站建設(shè)規(guī)范產(chǎn)品營銷方案案例范文
在Python中,運(yùn)算符重載是通過定義特殊方法(也稱為魔術(shù)方法)來實(shí)現(xiàn)的,這些特殊方法允許類的實(shí)例像內(nèi)置類型那樣使用運(yùn)算符。
Python提供了一系列這樣的特殊方法,用于重載各種運(yùn)算符。
以下是一些常見的運(yùn)算符重載特殊方法及其對(duì)應(yīng)的運(yùn)算符:
add(self, other):重載加法運(yùn)算符 +
sub(self, other):重載減法運(yùn)算符 -
mul(self, other):重載乘法運(yùn)算符 *
truediv(self, other):重載真除法運(yùn)算符 /(在Python 3中)
floordiv(self, other):重載整除法運(yùn)算符 //
mod(self, other):重載取模運(yùn)算符 %
pow(self, other[, modulo]):重載冪運(yùn)算符 **
radd(self, other):重載右加法運(yùn)算符(用于反向操作,例如當(dāng)左側(cè)操作數(shù)不是該類的實(shí)例時(shí))
iadd(self, other):重載就地加法運(yùn)算符(用于 +=)
eq(self, other):重載等于運(yùn)算符 ==
ne(self, other):重載不等于運(yùn)算符 !=
lt(self, other):重載小于運(yùn)算符 <
le(self, other):重載小于等于運(yùn)算符 <=
gt(self, other):重載大于運(yùn)算符 >
ge(self, other):重載大于等于運(yùn)算符 >=
以下是一個(gè)簡(jiǎn)單的Python示例,展示了如何重載加法運(yùn)算符 + 和等于運(yùn)算符 ==:
class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): if isinstance(other, Vector): return Vector(self.x + other.x, self.y + other.y) return NotImplemented def __eq__(self, other): if isinstance(other, Vector): return self.x == other.x and self.y == other.y return NotImplemented def __repr__(self): return f"Vector({self.x}, {self.y})" # 使用示例
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2 # 調(diào)用 __add__ 方法
print(v3) # 輸出: Vector(6, 8) v4 = Vector(2, 3)
print(v1 == v4) # 輸出: True
print(v1 == v2) # 輸出: False
在這個(gè)例子中,Vector 類定義了兩個(gè)特殊方法:add 和 eq。add 方法用于重載加法運(yùn)算符,允許兩個(gè) Vector 實(shí)例相加。eq 方法用于重載等于運(yùn)算符,允許比較兩個(gè) Vector 實(shí)例是否相等。
注意,當(dāng)重載運(yùn)算符時(shí),如果操作數(shù)類型不匹配,通常應(yīng)該返回 NotImplemented,這樣Python可以嘗試使用反向運(yùn)算符(例如,如果 a + b 不匹配,則嘗試 b.radd(a))。這是Python運(yùn)算符重載的一個(gè)約定俗成的做法,有助于保持代碼的靈活性和健壯性。