這篇文章給大家介紹Python中迭代器模式的原理是什么,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

1、簡單易用,與C/C++、Java、C# 等傳統(tǒng)語言相比,Python對代碼格式的要求沒有那么嚴(yán)格;2、Python屬于開源的,所有人都可以看到源代碼,并且可以被移植在許多平臺上使用;3、Python面向?qū)ο螅軌蛑С置嫦蜻^程編程,也支持面向?qū)ο缶幊蹋?、Python是一種解釋性語言,Python寫的程序不需要編譯成二進(jìn)制代碼,可以直接從源代碼運(yùn)行程序;5、Python功能強(qiáng)大,擁有的模塊眾多,基本能夠?qū)崿F(xiàn)所有的常見功能。
迭代器模式的demo:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
"""
大話設(shè)計(jì)模式
設(shè)計(jì)模式——迭代器模式
迭代器模式(Iterator Pattern):提供方法順序訪問一個(gè)聚合對象中各元素,而又不暴露該對象的內(nèi)部表示.
"""
#迭代器抽象類
class Iterator(object):
def First(self):
pass
def Next(self):
pass
def Isdone(self):
pass
def CurrItem(self):
pass
#聚集抽象類
class Aggregate(object):
def CreateIterator(self):
pass
#具體迭代器類
class ConcreteIterator(Iterator):
def __init__(self, aggregate):
self.aggregate = aggregate
self.curr = 0
def First(self):
return self.aggregate[0]
def Next(self):
ret = None
self.curr += 1
if self.curr < len(self.aggregate):
ret = self.aggregate[self.curr]
return ret
def Isdone(self):
return True if self.curr+1 >= len(self.aggregate) else False
def CurrItem(self):
return self.aggregate[self.curr]
#具體聚集類
class ConcreteAggregate(Aggregate):
def __init__(self):
self.ilist = []
def CreateIterator(self):
return ConcreteIterator(self)
class ConcreteIteratorDesc(Iterator):
def __init__(self, aggregate):
self.aggregate = aggregate
self.curr = len(aggregate)-1
def First(self):
return self.aggregate[-1]
def Next(self):
ret = None
self.curr -= 1
if self.curr >= 0:
ret = self.aggregate[self.curr]
return ret
def Isdone(self):
return True if self.curr-1<0 else False
def CurrItem(self):
return self.aggregate[self.curr]
if __name__=="__main__":
ca = ConcreteAggregate()
ca.ilist.append("大鳥")
ca.ilist.append("小菜")
ca.ilist.append("老外")
ca.ilist.append("小偷")
itor = ConcreteIterator(ca.ilist)
print itor.First()
while not itor.Isdone():
print itor.Next()
print "————倒序————"
itordesc = ConcreteIteratorDesc(ca.ilist)
print itordesc.First()
while not itordesc.Isdone():
print itordesc.Next()運(yùn)行結(jié)果:

上面類的設(shè)計(jì)如下圖:

關(guān)于Python中迭代器模式的原理是什么就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
網(wǎng)站欄目:Python中迭代器模式的原理是什么-創(chuàng)新互聯(lián)
新聞來源:http://www.yijiale78.com/article40/hocho.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供用戶體驗(yàn)、關(guān)鍵詞優(yōu)化、定制開發(fā)、外貿(mào)建站、云服務(wù)器、搜索引擎優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容