用特殊方法定制類 ***********************#特殊方法是Python 中用來擴充類的強有力的方式。它們可以實現(xiàn):# 模擬標準類型# 重載操作符#特殊方法允許類通過重載標準操作符+,*, 甚至包括分段下標及映射操作操作[] 來模擬標準#類型案狠。如同其它很多保留標識符窍帝,這些方法都是以雙下劃線(__)開始及結(jié)尾的吞琐。#下表列出了所有特殊方法及其它的描述#特殊方法 描述###基本定制型#C.__init__(self[, arg1, ...]) 構(gòu)造器(帶一些可選的參數(shù))#C.__new__(self[, arg1, ...]) 構(gòu)造器(帶一些可選的參數(shù));通常用在設(shè)置不變數(shù)據(jù)類型的子類。#C.__del__(self) 解構(gòu)器#C.__str__(self) 可打印的字符輸出萍程;內(nèi)建str()及print 語句#C.__repr__(self) 運行時的字符串輸出艺糜;內(nèi)建repr() 和‘‘ 操作符#C.__unicode__(self) Unicode 字符串輸出剧董;內(nèi)建unicode()#C.__call__(self, *args) 表示可調(diào)用的實例#C.__nonzero__(self) 為object 定義False 值;內(nèi)建bool() (從2.2 版開始)#C.__len__(self) “長度”(可用于類)破停;內(nèi)建len()####對象(值)比較c#C.__cmp__(self, obj) 對象比較翅楼;內(nèi)建cmp()#C.__lt__(self, obj) and 小于/小于或等于;對應(yīng)<及<=操作符#C.__gt__(self, obj) and 大于/大于或等于真慢;對應(yīng)>及>=操作符#C.__eq__(self, obj) and 等于/不等于毅臊;對應(yīng)==,!=及<>操作符######屬性#C.__getattr__(self, attr) 獲取屬性;內(nèi)建getattr()黑界;僅當(dāng)屬性沒有找到時調(diào)用#C.__setattr__(self, attr, val) 設(shè)置屬性#C.__delattr__(self, attr) 刪除屬性#C.__geta
ttribute__(self, attr) 獲取屬性褂微;內(nèi)建getattr();總是被調(diào)用#C.__get__(self, attr) (描述符)獲取屬性#C.__set__(self, attr, val) (描述符)設(shè)置屬性#C.__delete__(self, attr) (描述符)刪除屬性####數(shù)值類型:二進制操作符#C.__*add__(self, obj) 加园爷;+操作符#C.__*sub__(self, obj) 減宠蚂;-操作符#C.__*mul__(self, obj) 乘;*操作符#C.__*div__(self, obj) 除童社;/操作符#C.__*truediv__(self, obj) True 除求厕;/操作符#C.__*floordiv__(self, obj) Floor 除;//操作符#C.__*mod__(self, obj) 取模/取余扰楼;%操作符#C.__*divmod__(self, obj) 除和取模呀癣;內(nèi)建divmod()#C.__*pow__(self, obj[, mod]) 乘冪;內(nèi)建pow();**操作符#C.__*lshift__(self, obj) 左移位弦赖;<<操作符#C.__*rshift__(self, obj) 右移项栏;>>操作符#C.__*and__(self, obj) 按位與;&操作符#C.__*or__(self, obj) 按位或蹬竖;|操作符#C.__*xor__(self, obj) 按位與或沼沈;^操作符####數(shù)值類型:一元操作符#C.__neg__(self) 一元負#C.__pos__(self) 一元正#C.__abs__(self) 絕對值流酬;內(nèi)建abs()#C.__invert__(self) 按位求反;~操作符######數(shù)值類型:數(shù)值轉(zhuǎn)換#C.__complex__(self, com) 轉(zhuǎn)為complex(復(fù)數(shù));內(nèi)建complex()#C.__int__(self) 轉(zhuǎn)為int;內(nèi)建int()#C.__long__(self) 轉(zhuǎn)為long列另;內(nèi)建long()#C.__float__(self) 轉(zhuǎn)為float芽腾;內(nèi)建float()######數(shù)值類型:基本表示法(String)#C.__oct__(self) 八進制表示;內(nèi)建oct()#C.__hex__(self) 十六進制表示页衙;內(nèi)建hex()######數(shù)值類型:數(shù)值壓縮#C.__coerce__(self, num) 壓縮成同樣的數(shù)值類型摊滔;內(nèi)建coerce()#C.__index__(self) 在有必要時,壓縮可選的數(shù)值類型為整型(比如:用于切片索引等等)####序列類型#C.__len__(self) 序列中項的數(shù)目#C.__getitem__(self, ind) 得到單個序列元素#C.__setitem__(self, ind,val) 設(shè)置單個序列元素#C.__delitem__(self, ind) 刪除單個序列元素#C.__getslice__(self, ind1,ind2) 得到序列片斷#C.__setslice__(self, i1, i2,val)設(shè)置序列片斷#C.__delslice__(self, ind1,ind2) 刪除序列片斷#C.__contains__(self, val) 測試序列成員;內(nèi)建in 關(guān)鍵字#C.__*add__(self,obj) 串連店乐;+操作符#C.__*mul__(self,obj) 重復(fù)艰躺;*操作符#C.__iter__(self) 創(chuàng)建迭代類;內(nèi)建iter()######映射類型#C.__len__(self) mapping 中的項的數(shù)目#C.__hash__(self) 散列(hash)函數(shù)值#C.__getitem__(self,key) 得到給定鍵(key)的值#C.__setitem__(self,key,val) 設(shè)置給定鍵(key)的值#C.__delitem__(self,key) 刪除給定鍵(key)的值#C.__missing__(self,key) 給定鍵如果不存在字典中眨八,
則提供一個默認值## 12.1 簡單定制(RoundFloat2)#類的作用:保存浮點數(shù)腺兴,四舍五入,保留兩位小數(shù)位踪古。 通過斷言來控制輸入類型#class RoundFloatManual(object):# def __init__(self, val):# assert isinstance(val, float), \# "Value must be a float!"# self.value = round(val, 2)## def __str__(self):# return str(self.value)## __repr__ = __str__##C.__str__(self) 可打印的字符輸出卵渴;內(nèi)建str()及print 語句#C.__repr__(self) 運行時的字符串輸出溜腐;內(nèi)建repr() 和‘‘ 操作符#rfm=RoundFloatManual(8.888)#print(rfm)#-->8.89## 12.2 數(shù)值定制(Time60)#class Time60(object):# 'Time60 - track hours and minutes'## def __init__(self, hr, min):# 'Time60 constructor - takes hours and minutes'# self.hr = hr# self.min = min## def __str__(self):# 'Time60 - string representation'# return '%d:%d' % (self.hr, self.min)## __repr__ = __str__## def __add__(self, other):# 'Time60 - overloading the addition operator'# return self.__class__(self.hr + other.hr,self.min + other.min)# # def __iadd__(self, other):# 'Time60 - overloading in-place addition'# self.hr += other.hr# self.min += other.min# return self## 12.3 迭代器(RandSeq 和AnyIter)## RandSeq#from random import choice##class RandSeq(object):# def __init__(self, seq):# self.data = seq## def __iter__(self):# return self## def next(self):# return choice(self.data)## 任意項的迭代器(anyIter.py)#class AnyIter(object):# def __init__(self, data, safe=False):# self.safe = safe# self.iter = iter(data)## def __iter__(self):# return self## def next(self, howmany=1):# retval = []# for eachItem in range(howmany):# try:# retval.append(self.iter.next())# except StopIteration:# if self.safe:# break# else:# raise# return retval## 12.4 *多類型定制(NumStr)#class NumStr(object):# def __init__(self, num=0, string=''):# self.__num= num# self.__string = string## def __str__(self): # define for str()# return '[%d :: %r]' %(self.__num, self.__string)# # __repr__ = __str__## def __add__(self, other): # define for s+o# if isinstance(other, NumStr):# return self.__class__(self.__num + \# other.__num, \# self.__string + other.__string)# else:# raise TypeError('Illegal argument type for built-in operation')## def __mul__(self, num): # define for o*n# if isinstance(num, int):# return self.__class__(self.__num__ * num,self.__string__ * num)# else:# raise TypeError('Illegal argument type for built-in operation')## def __nonzero__(self):
# False if both are# return self.__num or len(self.__string)##a = NumStr(3, 'foo')#b = NumStr(3, 'goo')#c = NumStr(2, 'foo')#d = NumStr()#e = NumStr(string='boo')#f = NumStr(1)#print(a)#print(b)#print(c)#print(d)#print(e)#print(f)#-->#[3 :: 'foo']#[3 :: 'goo']#[2 :: 'foo']#[0 :: '']#[0 :: 'boo']#[1 :: '']