In front of the iterator and generator principle, it has been said that the __iter__ method and the role of the __next__ method, here do not repeat the description.
In this complement an example of implementing an iterator protocol.
Example 1: (The iterator generates an infinite value before the exception is thrown stopiteration)
Class C1:
def __init__ (Self,start):
Self.start = Start
def __iter__ (self):
return self
Def next (self):
Self.start + = 1
Return Self.start
O1 = C1 (10)
For I in O1:
Print I
Example 2: (After throwing an stopiteration exception)
Class C1:
def __init__ (self,start,stop):
Self.start = Start
Self.stop = Stop
def __iter__ (self):
return self
Def next (self):
If Self.start >= self.stop:
Raise Stopiteration
n = Self.start
Self.start + = 1
return n
O1 = C1 (1,10)
For I in O1:
Print I
Output:
1
2
3
4
5
6
7
8
9
Fibonacci Sequence:
Class Fib:
def __init__ (self):
Self._a=0
Self._b=1
def __iter__ (self):
return self
def __next__ (self):
Self._a,self._b=self._b,self._a + self._b
Return self._a
F1=FIB ()
This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1918569
8.python Object-oriented (implementation of an iterator protocol via __iter__,__next__) with Fibonacci sequence implementations