Python--29 魔法方法:定製序列

來源:互聯網
上載者:User

標籤:python   其他   self   values   rom   turn   protocol   color   是什麼   

協議是什嗎?

  協議(Protocols)與其他程式設計語言中的介面很相似,它規定你哪些方法必須要定義。然而,在Python中的協議就是現得不那麼正式。事實上,在Python中,協議更像是一種指南。

容器類型的協議

  如果希望定製的容器是不可變的話,你只需要定義__len__()和__getitem__()方法。

  如果你希望定製的容器是可變的話,除了__len__()和__getitem__()方法,你還需要定義__setitem__()和__delitem__()兩個方法。

聯絡要求

  編寫一個不可改變的自訂欄表,要求記錄列表中每個元素被訪問的次數。

>>> class CountList:...     def __init__(self,*args):...         self.values = [x for x in args]...         self.count = {}.fromkeys(range(len(self.values)),0)...     def __len__(self):...         return len(self.values)...     def __getitem__(self, key):...         self.count[key] += 1...         return self.values[key]... >>> c1 = CountList(1,3,5,7,9)>>> c2 = CountList(2,4,6,8,10)>>> c1[1]3>>> c2[1]4>>> c1[1] + c2[1]7>>> c1.count{0: 0, 1: 2, 2: 0, 3: 0, 4: 0}

 

Python--29 魔法方法:定製序列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.