python,通過__iter__/__next__得到一些類中迭代器的理解


在__iter__函數中將使__next__
中的StopIteration raise的條件歸
零,則可以循環迭代實例。
eg:

python3.3.5

class squares:
    def __init__(self, start, stop):
        self.flag = start - 1
        self.value = self.flag
        self.stop = stop
    def __iter__(self):
        self.value = self.flag
        return self
    def __next__(self):
        if self.value == self.stop:
            raise StopIteration
        self.value += 1
        return self.value

a = squares(1,5)
b = squares(1,5)
s = 0
while s<=41:
    for i in a:
        s= s + i
        print(s)

>>> 
1
3
6
10
15
16
18
21
25
30
31
33
36
40
45

  到45時迭代器停止工作,實現了三圈循環。

    可以得出:

迭代器走完一輪,拋出異常后,再次調用會先進行__iter__(),再進行__next__()。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM