引入
類的魔術方法是什麼:定義在類裏的特殊方法,一般格式爲__func__
有什麼用:方便的實現各種特定的功能。
下面簡單彙總下各種魔術方法,以後方便自己查閱。
魔術方法彙總
根據不同的功能,將其簡單分爲幾類。
構造和初始化
方法 | 功能 |
---|---|
__new__ (cls,other) | 創建類並返回這個類的實例 |
__init__(self, other) | 根據傳入參數初始化實例。注意與__new__的區別:實際在構造實例時,會先執行__new__創建並返回這個實例,然後再初始化屬性。兩者共同組成一個“構造函數” |
__del__(self) | 析構函數,再對象生命週期結束時調用 |
獲取類的信息
方法 | 功能 |
---|---|
__doc__(self) | 返回定義類時標註的字符串,默認是None |
__str__(self) | str() print實例時打印出來的內容 |
__repr__(self) | repr() |
__dir__(self) | dir() 返回所有的屬性和方法 |
__dict__(self) | 類調用:返回這個類中已經定義了的屬性和方法 實例調用:返回屬性的字典 |
__module__(self) | 返回類所在的模塊 |
__class__(self) | 實例調用,表明實例屬於哪個類 |
屬性訪問控制
方法 | 功能 |
---|---|
__getattr__(self, name) | 定義了你試圖訪問一個不存在的屬性時的行爲 |
__setattr__(self, name,value) | 定義了你對屬性進行賦值和修改操作時的行爲 |
__delattr__(self, name) | 定義的是你刪除屬性時的行爲 |
__getattribute__(self, name) | 定義了你的屬性被訪問時的行爲 |
重載運算符
算數運算符
方法 | 功能 |
---|---|
__add__(self, other) | + |
__sub__(self, other) | - |
__mul__(self, other) | * |
__div__(self, other) | / |
__floatdiv__(self, other) | // |
__mod__(self, other) | % |
__pow__(self, other) | ** |
比較運算符
方法 | 功能 |
---|---|
__lt__(self, other) | < |
__gt__(self, other) | > |
__le__(self, other) | <= |
__ge__(self, other) | >= |
__eq__(self, other) | == |
__ne__(self, other) | != |
位運算符
方法 | 功能 |
---|---|
__lshift__(self, other) | << |
__rshift__(self, other) | >> |
__and__(self, other) | & |
__or__(self, other) | | |
__xor__(self, other) | ^ |
注意:若對布爾變量(True,False)進行位運算,其等價於邏輯運算符。
賦值運算符
方法 | 功能 |
---|---|
__iadd__(self, other) | += |
__isub__(self, other) | -= |
__imul__(self, other) | *= |
__idiv__(self, other) | /= |
__ifloatdiv__(self, other) | //= |
__imod__(self, other) | %= |
__ipow__(self, other) | **= |
Unary Operators
方法 | 功能 |
---|---|
__neg__(self) | - |
__pos__(self) | + |
__abs__(self) | abs() |
__invert__(self) | ~ |
__round__(self) | round() |
__floor__(self) | floor() |
__ceil__(self) | ceil() |
類型轉換
方法 | 功能 |
---|---|
__complex__(self) | complex() |
__int__(self) | int() |
__long__(self) | long() |
__float__(self) | float() |
__oct__(self) | oct() |
__hex__(self) | hex() |
其他
方法 | 功能 |
---|---|
__call__(self, *args) | 實現該方法後,可像函數一樣直接調用實例。比如obj() |
未完待續…