Python中實現iterator

來源:互聯網
上載者:User

標籤:

今天和大家分享的是python開發中實現iterator的方法步驟,希望可以協助大家更好的學習和使用相關知識,一起來看看吧。

    建立了一個實體類,大致如下:

class Account():

def __init__(self,

account_name,

account_type,

account_cost,

return_amount=0):

self.account_name = account_name # 賬戶名

self.account_type = account_type # 賬戶類型

self.account_cost = account_cost # 月結費用

self.return_amount = return_amount # 返還金額

然後建立一個實體列表:

accounts = [Account("張三", "年費使用者", 450.00, 50),

Account("李四", "月結使用者", 100.00),

Account("楊不悔", "月結使用者", 190.00, 25),

Account("任我行", "月結使用者", 70.00, 10),

Account("淩未風", "年費使用者", 400.00, 40)]

我想要執行next()功能,也就是需要的時候“next”一下,得到List中的下一個元素。直接測試一下:

結果發現List不支援next()特性。這時候,List只是一個 iterable ,而不是 iterator 。 iterable 和 iterator 的區別如下:

. iterable —— 只實現了__iter__的對象;

. iterator —— 同時實現了__iter__和__next__方法的對象。

其中,__iter__返回 iterator 對象,__next__則返回迭代過程的下一個元素。

1. 讓列表成為 iterator

要讓前面的accounts List成為 iterator 只需簡單的一個iter()函數:

accounts_iterator = iter(accounts)

(next(accounts_iterator)).account_name

結果如所示:

這麼簡單的函數,估計還是有不少Python開發人員不知道吧?

2. 自訂 iterator 對象

擴充開來講,如何定義自己的 iterator 對象呢?其實也就是按照上面的定義,實現__iter__和__next__方法。

我們接下來定義一個AccountIterator類:

class AccountIterator():

def __init__(self, accounts):

self.accounts = accounts # 賬戶集合

self.index = 0

def __iter__(self):

return self

def __next__(self):

if self.index >= len(self.accounts):

raise StopIteration("到頭了...")

else:

self.index += 1

return self.accounts[self.index-1]

運行結果如:

通過這一陣折騰,next()功能就實現了。Python有不少意外的功能,還等著我們不斷去探究,也許這就是Python的魅力及極客之處。

 

文章來源:瓜園耕讀

  Python中實現iterator

聯繫我們

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