日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python iter next_python类中的__iter__, __next__与built-in的iter()函数举例

發布時間:2023/12/15 python 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()函数举例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。