注:本文所有代碼均經(jīng)過Python 3.7實(shí)際運(yùn)行檢驗(yàn)稀轨,保證其嚴(yán)謹(jǐn)性姿现。
本文閱讀時間約為3分鐘肠仪。
類的特殊方法
類的特殊方法(special method)也被稱作魔術(shù)方法(magic method)。
在類定義中出現(xiàn)的一些特殊方法备典,可以方便地使用Python中的一些內(nèi)置操作异旧。
所有特殊方法的名稱以兩個下劃線"__"(兩個連接著的下劃線)開始和結(jié)束。
對象構(gòu)造器
__init__(self, [...)
對象的構(gòu)造器提佣,實(shí)例化對象時調(diào)用吮蛹。
對象析構(gòu)器
銷毀對象時也有個特殊方法:
__del__(self, [...)
例子如下:
from os.path import join
class FileObject:
'''給文件對象進(jìn)行包裝從而確認(rèn)在刪除時文件流關(guān)閉'''
def __init__(self, filepath='~', filename='sample.txt'):
# 讀寫模式打開一個文件。
self.file = open(join(filepath, filename), 'r+')
def __del__(self):
self.file.close()
del self.file
算術(shù)運(yùn)算
算術(shù)操作符(從左向右計算拌屏,self作為左操作數(shù))
__add__(self, other): 使用+操作符潮针。
__sub__(self, other): 使用-操作符。
__mul__(self, other): 使用*操作符槐壳。
__div__(self, other): 使用/操作符然低。
反運(yùn)算(從右向左計算喜每,self作為右操作數(shù))
當(dāng)從左向右計算行不通务唐,左操作數(shù)不支持相應(yīng)操作時被調(diào)用:
__radd__(self, other): 使用+操作符。
__rsub__(self, other): 使用-操作符带兜。
__rmul__(self, other): 使用*操作符枫笛。
__rdiv__(self, other): 使用/操作符。
其中r表示right刚照,此時self是右操作數(shù)刑巧。
大小比較
__eq__(self, other):使用==操作符。equal
__ne__(self, other):使用!=操作符无畔。not equal
__lt__(self, other):使用<操作符啊楚。great than
__gt__(self, other):使用>操作符。less than
__le__(self, other):使用<=操作符浑彰。less and equal
__ge__(self, other):使用>=操作符恭理。great and equal
其它特殊方法
不僅數(shù)字類型可以使用+(或__add__())和-(或__sub__))等數(shù)學(xué)運(yùn)算符,例如字符串類型可以使用+進(jìn)行拼接郭变,使用*進(jìn)行賦值颜价。
__str__(self):自動轉(zhuǎn)換為字符串。
__repr__(self):返回一個用來表示對象的字符串诉濒。和上面的__str__(self)幾乎是一樣的功能周伦,只不過更正式。
__len__(self):返回元素個數(shù)未荒。
To be continued.