classFib (object):def __init__(self): SELF.A, self.b= 0, 1#Initialize two counters A, B def __iter__(self):returnSelf#The instance itself is an iterative object, so it returns itself defNext (self): SELF.A, self.b= self.b, SELF.A + self.b#Calculate Next Value ifSELF.A > 100000:#conditions for exiting a loop Raisestopiteration (); returnSelf.a#returns the next value
Implement an iterator that must contain both the __iter__ and next methods. There are two ways to use this class.
One, as a for loop to use:
for inch Fib (): ... Print n . ... 11235 ... 4636875025
Second, call the next method.
f = Fib () for in range :print f.next ()
Printing results:
11235813213455
One more example:
classA (object):def __init__(Self, O): Self.__obj__=odef __getattr__(self, name):ifHasattr (self.__obj__, name):returnGetAttr (self.__obj__, name)returnSelf.__dict__[Name]def __iter__(self):returnSelf.__obj__.__iter__() L=[]a=A (L) forIinchXrange (101): A.append (i)PrintSUM (a)
[Small knowledge] Python iterator-related @ python