這篇文章主要介紹了Python魔法方法 容器部方法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
為了加深印象,也為了以后能夠更好的回憶,還是記錄一下。
序列(類似集合,列表,字符串),映射(類似字典)基本上是元素的集合,要實現他們的基本行為(協議),不可變對象需要兩個協議,可變對象需要4個協議。
__len__(self):返回元素的數量,(為不可變對象需要的協議之一)=====> len __iter__返回一個迭代器,具有了__next__方法后,給for使用。 __contains__ 代表 in的意思 xx.__contains__ (22) ==>22 in xx一個效果 __getitem__(self, key)或者__getitem__(self, index), 返回執行輸入所關聯的值(為不可變對象需要的協議之一) __setitem__(self, key, values) 或者 __setitem__(self, index, values) , 設置指定輸入的值對應的values __delitem__ (self, key) 刪除指定key的值 __missing__這個有意思,跟__getattr__有的一比,是找不到這個key,觸發條件。前面用列表測試了,暈死了(只對字典有效。) __del__, 析構函數當這個類不存在實例對象時執行。下面我編寫一個自定義類似列表的類,實例后該類默認前面有10個None參數,且不能刪除前面5個空None。(隨口說的,開始寫了)
def check_index(index): if index < 5: raise IndexError('index must greater than 10') class S_List: def __init__(self): self.ll = [None] * 10 def __len__(self): # 提取參數長度 return len(self.ll) def __getitem__(self, index): # 取出參數 return self.ll[index] def __setitem__(self, index, value): # 設置參數 check_index(index) self.ll[index] = value def __delitem__(self, index): check_index(index) self.ll.pop(index) def __str__(self): # 打印對象時,輸出列表本身 return str(self.ll) def __del__(self): # 沒有手工刪除在程序結束時釋放 print('我被釋放了!') sl = S_List()del sl[3] print(isinstance(sl, S_List))print(f'輸出原始數據:{sl}')sl[6] = 'six'print(f'修改后原始數據:{sl}')print(f'隨便取一個值:{sl[1]}')del sl[6]print(f'第二次修改后原始數據:{sl}')del sl[3]# sl[4] = 'oh'print(sl)
正常輸出:
True輸出原始數據:[None, None, None, None, None, None, None, None, None, None]修改后原始數據:[None, None, None, None, None, None, 'six', None, None, None]隨便取一個值:None第二次修改后原始數據:[None, None, None, None, None, None, None, None, None][None, None, None, None, None, None, None, None, None]我被釋放了!
報錯提示:
Traceback (most recent call last): File "/Users/shijianzhong/Desktop/yunzuan_buy/study_base.py", line 81, in <module> del sl[3] File "/Users/shijianzhong/Desktop/yunzuan_buy/study_base.py", line 73, in __delitem__ check_index(index) File "/Users/shijianzhong/Desktop/yunzuan_buy/study_base.py", line 53, in check_index raise IndexError('index must greater than 10')IndexError: index must greater than 10我被釋放了!
這個是自定義的一個基本沒有什么方法的偽字典,不能增加元素,而且index,count等方法由于沒有寫入都無法使用。
好的方式是可以繼承list或者dict的類,在里面對需要的條件進行修改限制,這樣的話,實例出來的對象可以繼承原來的全部方法。
新聞熱點
疑難解答