據說,Python 的對象天生擁有一些神奇的方法,他們總被雙下劃線鎖包圍,他們是面向對象的python的一切.
他們是可以給你的類增加魔力的特殊方法,如果你的對象實現(重載)了這些方法的某一個,那么這個方法就會在特殊的情況下被python調用.
你可以定義自己想要的行為,而這一切都是自動發(fā)生的.
python 的魔術方法非常強大,然而隨之而來的則是責任,了解正確的方法去使用非常重要.
魔術方法如下:
基本魔術方法
__new__(cls [....])
a.__new__是在對象實例化的時候所調用的第一個方法
b. 他的第一個參數就是這個類,其他的參數就是用來直接傳遞給__init__方法
c.__new__決定是否使用該__init__方法,因為__new__可以調用其他類的構造方法或者直接返回別的實例化對象來作為本類的實例,如果__new__沒有返回實例對象,則__init__不會被調用
d.__new__主要是用于繼承一個不可變的類型,不如一個tuple(元祖)或者string(字符串)__init__(self,[....])構造器,當一個實例被創(chuàng)建的時候調用的初始化方法__del__(self)析構器,當一個實例被銷毀的時候調用分方法__call__(self,[...])允許一個類的實例像函數一樣被調用
a. 示例: x(a,b) 調用 x.__call__(a,b)__len__(self)定義當被len()調用時的行為__repr__(self)定義當被repr()調用時的行為 將對象轉化為供解釋器讀取的形式
s = '你好'
print(repr(s)) # '你好'
d = {'k':'v'}
print(repr(d)) # {'k': 'v'}
-
__str__(self)定義當被 str() 調用時的行為 -
__bytes__(self)定義當被 bytes() 調用時的行為 -
__hash__(self)定義當被 hash() 調用時的行為 可哈希不可變,不可變可哈希 -
__bool__(self)定義當被bool()調用時的行為,返回True或者False -
__format__(self,format_spec)定義當被 format() 調用時的行為主要用于字符串的格式化輸出
有關屬性
-
__getattr__(self,name)定義當用戶試圖獲取一個不存在的屬性(反射,獲取)
13.__getattrbute__(self,name)定義當該類的屬性被訪問時的行為 -
__setattr__(self,name,value)定義當一個屬性被設置時的行為 -
__delattr__(self,name)定義當一個屬性被刪除時的行為 -
__dir__(self,name)定義當dir()被調用時的行為 返回對象/模塊的屬性列表 -
__get__(self,instance,owner)定義當前描述符的值被獲取的行為 -
__set__(self,instance,value)定義當前描述符的值被改變的行為 -
__delete__(self,instance)定義當前描述符被刪除時的行為
比較操作符
-
__lt__(self,other)定義小于號的行為: x < y 調用 x.__lt__(y) -
__le__(self,other)定義小于等于號的行為: x <= y 調用 x.__le__(y) -
__eq__(self,other)定義等于號行為: x == y調用 x.__eq__(y) -
__ne__(self,other)定義不等于行為: x != y 調用 x.__ne__(y) -
__gt__(self,other)定義大于號行為: x > y 調用
x.__gt__(y) -
__ge__(self,other)定義大于等于行為: x >= y 調用 x.__ge__(y)
算法運算符
-
__add__(self,other)定義加法行為 + -
__sub__(self,other)定義減法行為 - -
__mul__(self,other)定義乘法行為 * -
__truediv__(self,other)定義除法行為 / -
__floordiv__(self,other)定義整除法行為 // -
__mod__(self,other)定義取余算法行為 % -
__divmod__(self,other)定義當被divmod()調用時的行為
余商函數: 返回 商和余數
print(divmod(5,3)) # ( 1,2 ) 商1余2
-
__pow__(self,other,[ modulo ])定義當被pow()調用或 ** (乘方) 運算時的行為
print(pow(2,3)) # 8
print( 2 ** 3 ) # 8
-
__lshift__(self,other)定義按位左移的行為 : << -
__rshift__(self,other)定位按位右移的行為: >> -
__add__(self,other)定義按位與操作行為:& -
__xor__(self,other)定義按位異或操作行為:~ -
__or__(self,other)定義按位或操作行為: |
反運算
-
__radd__(self,other)與上方相同,當左操作不支持相應的操作時被調用 -
__rsub__(self,other)與上方相同,當左操作數不支持相應的操作時被調用 -
__rmul__(self,other)與上方相同,當左操作數不支持相應的操作時被調用 -
__rtruediv__(self,other)與上方相同,當左操作數不支持相應的操作時被調用 -
__rfloordiv__(self,other)與上方相同,當左操作數不支持相應的操作時被調用 -
__rmod__(self,other)與上方相同,當左操作數不支持相應的操作時被調用 -
__rdivmod__(self,other)與上方相同,當左操作數不支持相應的操作時被調用 -
__rpow__(self,other)與上方相同,當左操作數不支持相應的操作時被調用 -
__rlshift__(self,other)與上方相同,當左操作數不支持相應的操作時被調用 -
__rrshift__(self,other)與上方相同,當左操作數不支持相應的操作時被調用 -
__rxor__(self,other)與上方相同,當左操作數不支持相應的操作時被調用 -
__ror__(self,other)與上方相同,當左操作數不支持相應的操作時被調用
增量賦值運算
-
__iadd__(self,other)定義賦值加法的行為: += -
__isub__(self,other)定義賦值減法的行為: -= -
__imul__(self,other)定義賦值乘法的行為: *= -
__itruediv__(self,other)定義賦值除法的行為: /= -
__ifloordiv__(self,other)定義賦值整除的行為: //= -
__imod__(self,other)定義賦值取余的行為: %= -
__ipow__(self.other, [...])定義賦值冪運算行為: **= -
__ilshift__(self,other)定義賦值按左位移動的行為: <<= -
__irshift__(self,other)定義賦值按右位移移動的行為: >>= -
__iand__(self,other)定義賦值 與操作的行為: &= -
__ixor__(self,other)定義賦值異或操作的行為: ^= -
__ior__(self,other)定義賦值或操作的行為: |=
一元操作符
-
__neg__(self)定義正號行為: +x -
__pos__(self)定義負號行為: -x -
__abs__(self)定義當被abs()調用時的行為返回數字的絕對值 -
__invert__(self)定義按位求反的行為: ~x
類型轉換
-
__complex__(self)定義當被complex調用時的行為 -
__int__(self)定義當被int()調用時的行為 -
__float__(self)定義當被float()調用時的行為 -
__round__(self, [ n ])定義當被round()調用時的行為 -
__index__(self)- 當對象是被應用在切片表達式中,實現整形強制轉換
- 如果你定義了一個可能在切片時候用到的定制的數值型,你應該定義
__index__ - 如果
__index__被定義,則__int__也需要被定義,且返回相同的值
上下文管理( with 語句 )
-
__enter__(self)- 定義當使用
with語句時的初始化行為 -
__enter__的返回值被with語句的目標或者as后的名字綁定
- 定義當使用
-
__exit__(self,exc_type,exc_value,traceback)- 定義當一個代碼被執(zhí)行或者終止后上下文管理器應該做什么
- 一般被用來處理異常,清除工作或者做一些代碼塊執(zhí)行完畢之后的日常工作
容器類型
-
__len__(self)定義當被len()調用時的行為(返回容器中元素的個數) -
__getitem__(self,key)定義獲取容器中指定元素的行為,相當于 dict[key] 獲取 value -
__setitem__(self,key,value)定義設置容器中指定元素的行為,相當于 dict[key] = value -
__delitem__(self,key)定義刪除容器中指定元素的行為,相當于 del dict[key] -
__iter__(self)定義當迭代容器中的元素行為
79.__reversed__(self)定義當被reversed()調用時的行為 -
__contains__(self,item)定義使用成員測試運算符(in 或 not in)時的行為