Python Generators and iterators

Source: Internet
Author: User

Iterator protocol

1. An iterator protocol means that an object must provide a next method that either returns the next item in the iteration, or causes a Stoplteration exception to terminate the iteration (only backward cannot go forward)

2. An iterative object: an object that implements an iterator protocol (how to: define an __iter__ () method within an Object)

3. The Protocol is a convention that iterates over an object, implements an iterator protocol, and Python's internal tools (such as a for loop, Sum,min,max function, etc.) Use an iterator protocol to access an Object.

Iterate: do one thing over and over again iterable (iterative) objects support the object that returns a member of its own each time
Object implements the __iter__ method
Sequence types, such as: list,str,tuple
Non-sequential types, such as: dict,file
Some user-defined classes that contain the __iter () or __getitem__ () methods

Dir (object) #查看对象有没有__iter__方法

l1. iter () #当你使用这个方法的时候, in memory, to help you reference or create an iterator to this object, we can use the __next () method

An iterator (iterator), also known as a cursor, is a software design pattern for programming, an interface that enables element traversal on container objects (container, such as lists, etc.)

Iterators are a special kind of data structure, in python, It also exists as an object.

Simple understanding Method: for each element in the collective, want to perform traversal, then for this collective iterator defines the traversal of each element in the collective order or method

Iterators are objects that follow the iteration protocol in Python
Use ITER () to get iterators from any sequence object to implement an iterator, you need to define the next () method in the class (python3 is __next__ ())
To make the iterator point to the next element, use the member function next ()
In python, the function next (), but not the member function throws a Stopiteration exception when there are no elements

The For loop can be used for any iterative object at the beginning of the for loop, which is passed to the ITER () built-in function via an iterative protocol, enabling an iterator to be obtained from an iterative object that contains the required next method

#这里显示的是内存对象通过i2. Next () Call just fine

1#iterator-based Protocol2 Li = [a.] 3 diedai_l = Li.__iter__() 4Print(diedai_l.__next__()) 5Print(diedai_l.__next__()) 6Print(diedai_l.__next__()) 7#print (diedai_l.__next__ ()) # out of bounds error8 9# subscript10Print(li[0])11Print(li[1])12Print(li[2])13#Print (li[3]) # Beyond the border error14 15#simulating A For loop mechanism with a while loopdiedai_l = Li.__iter__()17 whileTrue:18Try:19Print(diedai_l.__next__())20exceptstopiteration:21stPrint("Iteration complete, Loop terminated")22 break23 24#for Loop access Mode25#The For Loop essence is to follow the access method of the iterator protocol, first calling the Diedai_l=li.__iter__ method26#or directly diedai_l=iter (l), then execute diedai_l.__next__ () in turn until you capture the27#stopitearation terminating Loop28#for Loop The essence of all objects is the same principle
iter and Next instances

The yield effect is to create a generator object that uses yield in the function and returns a generator object

The offset and element range can be used to generate an index offset in a non-exhaustive traversal, but not an element at offset if both the offset and offset elements are required, you can use the enumerate () function to return a generator object with this built-in function

‘www.baidu.com‘>>> enumerate(url)    #发现是个内存对象证明这个内置函数是一个生成器对象<enumerate object at 0x000000000217D3A8>>>> g1 = enumerate(url)>>> g1.next()(0, ‘w‘)

Generator function: The function body contains the yield keyword, and the result of the function is the generator function #生成器本身是迭代器

#yield的功能: 1. Similar to return, you can return a value, but in a different place, yield can return multiple values, and return can only be returned once.

2. Encapsulates the __iter__ and __next__ methods for the function, and makes the result of the Function's execution an iterator

3. Follow the Iterator's value method, obj. Next (), the execution of the function is triggered, the function is paused and the state in the continuation is saved by yield

If you call the yield method in a function, it returns a generator object

1 defFoo ():2     Print("Here we go.")3First =yield #return 1 first = None4     Print("First time", First)5     yield26     Print("second time")7t =Test ()8 Print(test ().__next__())9res = T.__next__()#Next (t)Ten Print(res) oneres = T.send ("the function stays in the first place, and I'm assigning first to First.") a Print(res) -  - Output Results the Here we go. - None - Here we go. - None + the first time the function is in the same position, I'm assigning -2
yield function

 

Python Generators and iterators

Related Article

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.