開發者學堂課程【Python 語言基礎 3:函數、面向對象、異常處理:特殊方法】學習筆記,與課程緊密聯系,讓使用者快速學習知識。
課程位址:
https://developer.aliyun.com/learning/course/601/detail/8757特殊方法
内容簡介:
一、 特殊方法含義
二、 文檔位置
三、 特殊方法介紹
一、特殊方法含義
特殊方法也稱為魔術方法,特殊方法都是使用_開頭和結尾的;特殊方法一般不需要我們手動調用,需要在一些特殊情況下自動執行。
二、文檔位置
Language Reference(語言參考)—Data model(資料模型)—Special method names(特殊方法名字)列出所有特殊方法的名字位置。
三、特殊方法介紹
執行個體:
定義一個 Person 類
class Person(object):
“““人類”””
def _init_(self,name,age):
self.name = name
self.age = age
1. _str_() 特殊方法
_str_() 這個特殊方法會在嘗試将對象轉換為字元串的時候調用
它的作用可以用來指定對象轉換為字元串的結果(print函數)
def _str_(self):
return ‘ Person [name=%s , age=%d]’%(self.name,self.sge)
建立兩個 person 類的執行個體
p1 = Person(‘孫悟空’,18)
p2 = Person(‘豬八戒’,28)
列印 p1
當列印一個對象時,實際上列印的是對象中特殊方法 _str_() 的傳回值
Print (p1)
2. _repr_() 特殊方法
_repr_() 這個特殊方法會在對目前對象使用 repr() 函數時調用
它的作用是指定對象在‘互動模式’中直接輸出的效果
def _repr_(self):
return ‘Hello’
print(repr(p1))列印得出
3. _gt_特殊方法
_gt_會在對象做大于比較的時候調用,該方法的傳回值将會作為比較的結果
它需要兩個參數,一個 self 表示目前對象,other 表示和目前對象比較的對象
def _gt_(self,other):
return self.age > other.age
print(p1 > p2)
print(p2 > p1)
關于大于小于等于的特殊方法:
object._lt_(self,other) 小于<
object._le_(self,other) 小于等于<=
object._eq_(self,other) 等于==
object._ne_(self,other) 不等于!=
object._gt_(self,other) 大于>
object._ge_(self,other) 大于等于>=
4. 擷取長度的 _len_() 方 法
_len_() 擷取對象的長度
5.布爾特殊方法
object._bool_(self) 可以通過 bool 來指定對象轉換為布爾值的情況
def _bool_(self):
return self.age > 17
print(bool(p1))列印得出
If p1:
print(p1.name,’已經成年了’)
else:
print(p1.name,’還未成年了’)
6.對對象做加法減法的特殊方法介紹
object._add_(self,other)
object._sub_(self,other)
object._mul_(self,other)
object._matmul_(self,other)
object._truediv_(self,other)
object._floordiv_(self,other)
object._mod_(self,other)
object._divmod_(self,other)
object._pow_(self,other[,modulo])
object._lshift_(self,other)
object._rshift_(self,other)
object._and_(self,other)
object._xor_(self,other)
object._or_(self,other)