Python Learning iterations in -40.python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.