python-魔法方法-算術運算與反算術運算

我們知道語句:

a = int(‘3’)
b = int('2')

是將類int實例化的過程.
這在本人介紹工廠函數的博客中有過介紹

當python遇到“+”號時,會自動調用__add__方法。

class Nint(int)def __add__(self,other):
		return int(self)+int(other)

在這裏前面的實例:a是self,b是other。

如果在實例:a中找不到__add__方法,那麼會自動調用b中的__radd__方法

class Nint(int):
	def __radd__(self,other):
		rethrn int(self)+int(other)

這時,b是self,而a爲other。(因爲__radd__是實例b的方法)
例如:

>>> 1+b		# 數字1找不到__add__,則自動調用b中的__radd__
>>> 3     # 實際執行的是:b+1

注意:1+b與b+1順序並不相同。
如果是減號、除號,則計算結果也會不同

魔法方法中的運算方法與反運算方法:

運算方法 當遇到該符號調用
add(self, other) +
sub(self, other) -
mul(self, other) *
truediv(self, other) /
floordiv(self, other) //
mod(self, other) %
divmod(self, other) 當被 divmod() 調用時的行爲
pow(self, other[, modulo]) 當被 power() 調用或 ** 運算時的行爲
lshift(self, other) 左移位:<<
rshift(self, other) 右移位:>>
and(self, other) &
xor(self, other) 異或運算:^
or(self, other) 或:

反運算:(與上方相同,當左操作數不支持相應的操作時被調用)
在名字在前面加上r即可:
radd(self, other)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章