python iter next_python类中的__iter__, __next__与built-in的iter()函数举例
i1 = iter(itr, 'c')
這個意思是說,返回itr的iterator,而且在之后的迭代之中,迭代出來'c'就立馬停止。對這個itr有什么要求呢?這個itr在這里必須是callable的,即要實現__call__函數
再說傳一個參數,有
i2 = iter(itr)這里itr必須實現__iter__函數,這個函數的返回值必須返回一個iterator對象
看例子:
class Itr(object):
def __init__(self):
self.result = ['a', 'b', 'c', 'd']
self.i = iter(self.result)
def __call__(self):
res = next(self.i)
print("__call__ called, which would return ", res)
return res
def __iter__(self):
print("__iter__ called")
return iter(self.result)
itr = Itr()
# i1必須是callable的,否則無法返回callable-iterator
i1 = iter(itr, 'c')
print("i1 = ", i1)
# i2只需要類實現__iter__函數即可返回
i2 = iter(itr)
print("i2 = ", i2)
for i in i1:
print(i)
for i in i2:
print(i)
輸出結果是:
i1 =
__iter__ called
i2 =
__call__ called, which would return a
a
__call__ called, which would return b
b
__call__ called, which would return c
a
b
c
d
可以看到傳入兩個參數的i1的類型是一個callable_iterator,它每次在調用的時候,都會調用__cal__函數,并且最后到c就停止了。
而i2就簡單的多,itr把自己類中一個容器的迭代器返回就可以了。
有朋友可能不滿意,對上面的例子只是為了介紹iter()函數傳兩個參數的功能而寫,如果真正想寫一個iterator的類,需要使用__next__函數。這個函數每次返回一個值就可以實現迭代了。
class Next(object):
def __init__(self, data = 1):
self.data = data
def __iter__(self):
return self
def __next__(self):
print("__next__ called")
if self.data > 5:
raise StopIteration
else:
self.data += 1
return self.data
for i in Next(3):
print(i)
輸出結果是:
__next__ called
4
__next__ called
5
__next__ called
6
__next__ called
很簡單把。唯一需要注意下的就是__next__中必須控制iterator的結束條件,不然就死循環了。
分享到:
2012-05-06 15:20
瀏覽 27787
評論
2 樓
rushwoo
2015-09-13
這樣就可以了:
def next(self):
print("__next__ called")
if self.data > 5:
raise StopIteration
else:
self.data += 1
return self.data
是不是和版本有關系
1 樓
rushwoo
2015-09-13
報錯啊:
for i in Next(3):
TypeError: iter() returned non-iterator of type 'Next'
總結
以上是生活随笔為你收集整理的python iter next_python类中的__iter__, __next__与built-in的iter()函数举例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql dba管理_Mysql DB
- 下一篇: 朋友圈九宫格图片是怎么制作的 朋友圈九宫