Iterator, yield expression, generator, coroutine, and iteratorcoroutine in Python

Source: Internet
Author: User

Iterator, yield expression, generator, coroutine, and iteratorcoroutine in Python

Every time I look at the code written by others, I have yield. I feel like a super geek. Today I will spend some time organizing it.

In order:

1. iterator

Iterator is called an iterator used to traverse serialized data, such as a list or set. If an object wants to be able to be traversed by an iterator, as long as the _ iter _ () method is added to the class of this object, this method returns an iterator object. The next () method must be implemented in the iterator object, as shown in the following example:

>>> class sequenceClass(object):...     def __init__(self, *args):...             self._data = list(args)...     def __iter__(self):...             return DataIter(self)...>>> class DataIter(object):...     def __init__(self, data):...             self._index = 0...             self._data = data._data...     def next(self):...             if self._index >= len(self._data): raise StopIteration()...             d = self._data[self._index]...             self._index += 1...             return d... >>> data = sequenceClass(1,2,3,4)>>> for x in data: print x... 1234
The execution method is as follows:

Create object data: data = sequenceClass (1, 2, 3, 4)
Use for loop to traverse data:

1. When the first for loop traverses data, the _ iter _ () method of data is called. This method returns an iterator object: DataIter.

2. next, the for loop calls the next () method of the DataIter object each time, and the next () method returns data.

3. When the data traversal is complete, an exception StopIteration is thrown. The exception is caught by the for loop and the traversal ends.

The above is the implementation method of iterator, but there is a simpler method, but it may not be easy to understand at the beginning, that is, the yield expression is used to traverse objects.


2. yield Expression and genetator

In Python, a generator object is returned when a function containing yield is called. The purpose of the generator design is to implement the iterator protocol in a simpler way. For example, in the above example, you need to write a separate class to traverse data, while using generator, A yield expression can be used as an iterator.

Let's look at an example:

>>> def test_generator():...     s = 0...     for i in xrange(10):...             s = yield i * s...             print 'i:', i...             print 's:', s...             print 'i * s', i * s... >>> t = test_generator()>>> t<generator object test_generator at 0x10403a820>>>> >>> t.next()0>>> t.send(10)i: 0s: 10i * s 010>>> t.send(11)i: 1s: 11i * s 1122

Step by step:

1. Define a function named test_generator.

2. Call test_generator to obtain the t object.

3. When running t, it is a generator object

4. t. next () or t. send (None) starts the generator object. The generator object runs to yield, returns the value of the expression on the Right of yield, and saves the current shape of the generator object. Therefore, none of the subsequent prints were executed.

5. t. send (10)

1) Assign the input value 10 to s.

2) execute the expression following yield to finish all print execution. The parsing is as follows:

Because the current state of the object is saved in step 1 generator, I = 0, s is the input value of 10, and I * s is of course 0, next, enter the next loop. At this time, I = 1. Execute the yield expression. The result is 10. Save the current generator status, return 10, and generator stops running.

6. t. send (11)

1) similar to step 1, input 11 to s

2) in step 2, generator saves the value of the current object. Therefore, I = 1, s is the input value of 11, and I * s is of course 11, next, enter the next loop. At this time, I = 2. Execute the yield expression. The result is 22. Save the current generator status, return 22, and generator stops running.

7. Next, call t. send (num), which is the same as step 5 and 6 until the cycle inside the generator is completed. When the call is made again, an exception will be thrown: StopIteration


Summary:

1. yield Expression, four forms:

A. The input value or the input value is None.

Yield 1

B. Accept input values

S = yield 1

C. input is accepted, but no data is returned. By default, None is returned.

S = yield

D. Neither input nor return value are accepted. None is returned by default.

Yield

First, when the function calls yield, it returns the calculated value to the right of yield. Here, the calculation means that yield can be written as a function or expression,

Type 2: When a function is called to yield, a value must be input. The value is stored in s, and the value of the expression following yield is returned and saved to the current state.

Third: only accept the data and then execute the yield statement. When the statement is executed again to yield, save the current state and return the result.

Only some messages are printed, without the result.

Type 4: the data in the generator can only be traversed.

2. Benefits of using generator:

1) it is convenient to implement the iterator, that is, yield does not accept the input value.

2) using generator can reduce the memory usage, because the retrieved values are calculated each time, and you do not need to compute them all at once.

Traversal, and finally release it. In addition, you can perform some operations after yield to control the return value at will.


3. coroutine

If you use the yield function, if you use send for control, even if coroutine is used, if you use the for loop for control, even if generator or iterator, the usage is mostly seen in

Decorator, such as gen. coroutine in tornado.

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.