python 中的 __getitem__, __iter__ 和__next__

來源:互聯網
上載者:User

標籤:迭代器   列表   iterable   ror   ble   __init__   結束   多態   下標   

首先先簡單介紹一下這幾個內建函數:

__getitem__:根據傳入的int參數,返回一個列表中的元素

__iter__:返回一個可迭代對象

__next__:當被迭代時,返回下一個迭代的對象

查了點資料,來源:知乎 連結:https://www.zhihu.com/question/44015086/answer/119281039 靈劍

  這是個和多態有關的問題,Python中關於迭代有兩個概念,第一個是Iterable,第二個是Iterator,協議規定Iterable的__iter__方法會返回一個Iterator, Iterator的__next__方法(Python 2裡是next)會返回下一個迭代對象,如果迭代結束則拋出StopIteration異常。
同時,Iterator自己也是一種Iterable,所以也需要實現Iterable的介面,也就是__iter__,這樣在for當中兩者都可以使用。我的理解是,如果這個對象被for時,會首先調用__iter__方法返回一個iterator,然後再對這個iterator迴圈調用__next__方法,直到碰到StopIteration時則停止退出 如果for的對象沒有__iter__方法,則無法獲得一個迭代器,那麼就會報錯,但是,如果這個類實現了__getitem__方法,會從0開始依次讀取相應的下標,直到發生IndexError為止,str類就沒有實現了_iter_方法,所以我們可以for一個str對象,讓它的每一個字母都列印輸出,接下來附一個經典的FIB類增加理解: class Fib(object):
def __init__(self):
self.a = 0
self.b = 1

def next(self):
self.a , self.b = self.b , self.a + self.bif self.b > 1000:  raise StopIteration
return self.a

def __iter__(self):
return self

python 中的 __getitem__, __iter__ 和__next__

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.