運(yùn)算符相關(guān)的魔術(shù)方法
運(yùn)算符相關(guān)的魔術(shù)方法實(shí)在太多了,j就大概列舉下面兩類(lèi):
1、比較運(yùn)算符
魔術(shù)方法 | 說(shuō)明 |
__cmp__(self, other) | 如果該方法返回負(fù)數(shù),說(shuō)明 self < other; 返回正數(shù),說(shuō)明 self > other; 返回 0 說(shuō)明 self == other 。強(qiáng)烈不推薦來(lái)定義 __cmp__ , 取而代之, 最好分別定義 __lt__, __eq__ 等方法從而實(shí)現(xiàn)比較功能。 __cmp__ 在 Python3 中被廢棄了。 |
__eq__(self, other) | 定義了比較操作符 == 的行為 |
__ne__(self, other) | 定義了比較操作符 != 的行為 |
__lt__(self, other)? | 定義了比較操作符 < 的行為 |
__gt__(self, other) | 定義了比較操作符 > 的行為 |
__le__(self, other) | ?定義了比較操作符 <= 的行為 |
__ge__(self, other)? | 定義了比較操作符 >= 的行為 |
來(lái)看個(gè)簡(jiǎn)單的例子就能理解了:
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- class Number(object): def __init__(self, value): self.value = value def __eq__(self, other): print('__eq__') return self.value == other.value def __ne__(self, other): print('__ne__') return self.value != other.value def __lt__(self, other): print('__lt__') return self.value < other.value def __gt__(self, other): print('__gt__') return self.value > other.value def __le__(self, other): print('__le__') return self.value <= other.value def __ge__(self, other): print('__ge__') return self.value >= other.value if __name__ == '__main__': num1 = Number(2) num2 = Number(3) print('num1 == num2 ? --------> {} \n'.format(num1 == num2)) print('num1 != num2 ? --------> {} \n'.format(num1 == num2)) print('num1 < num2 ? --------> {} \n'.format(num1 < num2)) print('num1 > num2 ? --------> {} \n'.format(num1 > num2)) print('num1 <= num2 ? --------> {} \n'.format(num1 <= num2)) print('num1 >= num2 ? --------> {} \n'.format(num1 >= num2))
輸出的結(jié)果為:
__eq__ num1 == num2 ? --------> False __eq__ num1 != num2 ? --------> False __lt__ num1 < num2 ? --------> True __gt__ num1 > num2 ? --------> False __le__ num1 <= num2 ? --------> True __ge__ num1 >= num2 ? --------> False
2、算術(shù)運(yùn)算符
魔術(shù)方法 | 說(shuō)明 |
__add__(self, other)? | 實(shí)現(xiàn)了加號(hào)運(yùn)算 |
__sub__(self, other) | 實(shí)現(xiàn)了減號(hào)運(yùn)算 |
__mul__(self, other)? | 實(shí)現(xiàn)了乘法運(yùn)算 |
__floordiv__(self, other)? | 實(shí)現(xiàn)了// 運(yùn)算符 |
___div__(self, other)? | 實(shí)現(xiàn)了/運(yùn)算符. 該方法在Python3 中廢棄. 原因是Python3 中,division 默認(rèn)就是true division |
?__truediv__(self, other)? | 實(shí)現(xiàn)了true division. 只有你聲明了from __future__ import division 該方法才會(huì)生效 |
__mod__(self, other)? | 實(shí)現(xiàn)了% 運(yùn)算符, 取余運(yùn)算 |
__divmod__(self, other)? | 實(shí)現(xiàn)了divmod() 內(nèi)建函數(shù) |
__pow__(self, other)? | 實(shí)現(xiàn)了** 操作. N 次方操作 |
__lshift__(self, other)? | 實(shí)現(xiàn)了位操作<< |
__rshift__(self, other)? | 實(shí)現(xiàn)了位操作>> |
__and__(self, other)? | 實(shí)現(xiàn)了位操作& |
__or__(self, other)? | 實(shí)現(xiàn)了位操作` |
__xor__(self, other)? | 實(shí)現(xiàn)了位操作^ |