運算符相關的魔術方法
運算子相關的魔術方法實在太多了,j就大概列舉下面兩類:
1、比較運算子
| 魔術方法 | 說明 |
| #__cmp__(self, other) | 如果此方法傳回負數,說明self < other; 傳回正數,說明self > other; 回傳0 說明self == other 。強烈不建議來定義 __cmp__ , 取而代之, 最好分別定義 __lt__, __eq__ 等方法從而實現比較功能。 __cmp__ 在 Python3 中被廢棄了。 |
| __eq__(self, other) | 定義了比較運算子== 的行為 |
| __ne__(self, other ) | 定義了比較運算子!= 的行為 |
| __lt__(self, other) | 定義了比較運算子< 的行為 |
| __gt__(self, other) | 定義了比較運算子> 的行為 |
| __le__(self, other) | 定義了比較運算子<= 的行為 |
| __ge__(self, other) | 定義了比較運算子>= 的行為 |
來看個簡單的例子就能理解了:
#!/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))輸出的結果為:
__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、算術運算子
| 魔術方法 | 說明 |
| __add__(self, other) | 实现了加号运算 |
| __sub__(self, other) | 实现了减号运算 |
| __mul__(self, other) | 实现了乘法运算 |
| __floordiv__(self, other) | 实现了 // 运算符 |
| ___div__(self, other) | 实现了/运算符. 该方法在 Python3 中废弃. 原因是 Python3 中,division 默认就是 true division |
| __truediv__(self, other) | 实现了 true division. 只有你声明了 from __future__ import division 该方法才会生效 |
| __mod__(self, other) | 实现了 % 运算符, 取余运算 |
| __divmod__(self, other) | 实现了 divmod() 內建函数 |
| __pow__(self, other) | 实现了 ** 操作. N 次方操作 |
| __lshift__(self, other) | 实现了位操作 << |
| __rshift__(self, other) | 实现了位操作 >> |
| __and__(self, other) | 实现了位操作 & |
| __or__(self, other) | 实现了位操作 ` |
| __xor__(self, other) | 实现了位操作 ^ |
##
新建檔案
預覽
Clear
- 課程推薦
- 課件下載
課件暫不提供下載,工作人員正在整理中,後期請多關注該課程~ 















