重載方法格式:
def __xxx__(self,other):
...
注:重載方法格式
-----------------------------------------------------------------運算符
運算符重載:
作用:
讓自定義的類創建的對象像內建對象一樣進項運算符操作
算數運算符:
__add__ 加法 +
__sub__ 減法 -
__mul__ 乘法 *
__truedif__ 除法 /
__floordiv__ 地板除 //
__mod__ 取模(求余) %
__pow__ 冪 **
反向算數運算符重載:
__radd__(self, lhs) # 加法 lhs + self
__rsub__(self, lhs) # 減法 lhs + self
__rmul__(self, lhs) # 乘法 lhs * self
__rtruediv__(self, lhs) # 除法 lhs / self
__rfloordiv__(self, lhs) # 地板除 lhs // self
__rmod__(self, lhs) # 取模 lhs % self
__rpow__(self, lhs) # 冪運算 lhs ** self
注:lhs(left hand side) 左手邊
復合賦值算數運算符的重載:
__iadd__(self, other) # 加法 self += other
__isub__(self, other) # 減法 self -= other
__imul__(self, other) # 乘法 self *= other
__itruediv__(self, other) # 除法 self /= other
__ifloordiv__(self, other) # 地板除 self //= other
__imod__(self, other) # 取模 self %= other
__ipow__(self, other) # 冪運算 self **= other
注:當重載后優先使用重載的方法,否則使用__add__等方法代替
-----------------------------------------------------------------比較運算符
比較運算符重載:
__lt__ 小於 <
__le__ 大於等於 <=
__gt__ 大於 >
__ge__ 大於等於 >=
__eq__ 等於 ==
__ne__ 不等於 !=
-----------------------------------------------------------------位操作運算符
位操作運算符重載:
__and__ 位與 &
__or__ 位或 |
__xor__ 位異或 ^
__lshift__ 左移 <<
__rshift__ 右移 >>
反向位操作運算符:
__rand__ 位與 &
__ror__ 位或 |
__rxor__ 位異或 ^
__rlshift__ 左移 <<
__rrshift__ 右移 >>
復合賦值位運算符重載:
__iand__ 位與 &
__ior__ 位或 |
__ixor__ 位異或 ^
__ilshift__ 左移 <<
__irshift__ 右移 >>
-----------------------------------------------------------------一元運算符
一元運算符的重載:
__neg__ 符號 -
__pos__ 正號 +
__invert__ 取反 ~
重載格式:
def __xxx__(self):
pass
-----------------------------------------------------------------內建函數
內建函數重載:
def __abs__(self) abs(obj) 函數調用
def __len__(self) len(obj) 函數調用
def __reversed__(self) reversed(obj) 函數調用
def __round__(self) round(obj) 函數調用
-----------------------------------------------------------------數值轉換函數
數值轉換函數重載:
__int__ int(obj)
__float__ float(obj)
__complex__ complex(obj)
__bool__ bool(obj)
-----------------------------------------------------------------布爾測試運算符
布爾測試運算符重載:
格式:
def __bool__(self):
....
作用:
1) 用於bool(obj) 函數取值
2) 用於if語句真值表達式中
3) 用於while語句真值表達式中
重載說明:
當沒有 __bool__(self) 方法時,真值測試將取
__len__(self) 方法的返回值來測試布爾值
-----------------------------------------------------------------in / not in
in / not in 運算符重載:
格式:
def __contains__(self, e):
...
作用:
成員資格測試(通常)
-----------------------------------------------------------------索引和切片
索引和切片運算符的重載:
重載方法:
__getitem__(self, i) 方法
__sefitem__(self, i, v) 方法
__delitem__(self, i) 方法
作用:
讓自定義類型的對象能進行索引和切片操作
切片(slice)重載:
切片重載同性索引重載公用的方法
__getitem__(self, i) 切片取值
__sefitem__(self, i, v) 切片賦值
__delitem__(self, i) del切片刪除
-----------------------------------------------------------------迭代器重載
迭代器:
__next__(self):
可迭代對象:
__iter__(self):
-----------------------------------------------------------------with環境管理器類內重載
類內有__enter__ 和 __exit__ 方法的類被稱為環境管理器
能夠用with進行管理的對象必須是環境管理器
__enter__ 方法將在進入 with 語句時被調用返回由 as 變量管理的對象
__exit__ 方法將在離開with語句時被調用,且可以用參數來判斷離開with語句時是否有異常發生並作出相應的處理