據說,Python 的對象天生擁有一些神奇的方法,它們總被雙下劃線所包圍,他們是面向對象的 Python 的一切。
他們是可以給你的類增加魔力的特殊方法,如果你的對象實現(重載)了這些方法中的某一個,那么這個方法就會在特殊的情況下被 Python 所調用,你可以定義自己想要的行為,而這一切都是自動發生的。
Python 的魔術方法非常強大,然而隨之而來的則是責任。了解正確的方法去使用非常重要!
魔法方法
含義
基本的魔法方法
__new__(cls[, ...])
__del__(self) 析構器,當一個實例被銷毀的時候調用的方法
__call__(self[, args...]) 允許一個類的實例像函數一樣被調用:x(a, b) 調用 x.__call__(a, b)
__len__(self) 定義當被 len() 調用時的行為
__repr__(self) 定義當被 repr() 調用時的行為
__str__(self) 定義當被 str() 調用時的行為 類似于Java中toString方法
__bytes__(self) 定義當被 bytes() 調用時的行為
__hash__(self) 定義當被 hash() 調用時的行為
__bool__(self) 定義當被 bool() 調用時的行為,應該返回 True 或 False
__format__(self, format_spec) 定義當被 format() 調用時的行為
有關屬性
__getattr__(self, name) 定義當用戶試圖獲取一個不存在的屬性時的行為
__getattribute__(self, name) 定義當該類的屬性被訪問時的行為
__setattr__(self, name, value) 定義當一個屬性被設置時的行為
__delattr__(self, name) 定義當一個屬性被刪除時的行為
__dir__(self) 定義當 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)
新聞熱點
疑難解答