In the previous article, we used the generator to create an object that could be traversed. In which we used the yield keyword.
Python I am also learning, so I am not familiar with the nature of yield, but in C #, the yield keyword is the syntactic sugar, which maintains an iterative state (for the array in C #, which is the currently traversed element subscript).
So, is it a syntactic sugar in python, too? First of all, we know that the generator produces an object, and this object can be traversed, reference C #, in C # The object that can be foreach has the GetEnumerator method. Well, there are some ways in python that can be used to make the object traverse.
Lenovo, finishing:
Object--class
Method--most likely a retention method with underscores like a constructor (__init__).
According to "in-depth Python3", sure enough.
Code on:
1 classFib:2 def __init__(Self,max):3Self.max =Max4 def __iter__(self):5SELF.N =06SELF.A =07SELF.B = 18 return Self9 def __next__(self):Ten ifSELF.N >=Self.max: One Raisestopiteration AFIB =self.b -self.a,self.b = SELF.B,SELF.A +self.b -Self.n+=1 the returnfib - - forIinchFib (10): - Print(i)
The effect is the same as the previous one, visible yield is also a grammatical sugar, it helps us to secretly realize the __iter__ and __next__ two methods.
So now we can conclude that, at the beginning of the traversal, the object's __iter__ method is called (without error, of course), the method is responsible for initializing the parameters required to traverse, and then at the time of traversal, the call is the __next__ method, the return value of the method as the value of the second traversal. If the traversal ends, a stopiteration error is thrown, and for will handle the error and end the traversal. It is very different from C # to end the traversal in a way that throws an error.
Python Learning iterations in -40.python