Home > Article > Backend Development > Introduction to the Python keyword yield
Coroutines are a way to develop asynchronous I/O code in Tornado. The coroutine uses the Python keyword yield to suspend and resume execution of the caller. So before learning about coroutines, we must first familiarize ourselves with the concept and usage of yield. To understand yield, we need to first understand the concept of iterators.
In Python, an iterator defined using the yield keyword is also called a [generator]The most commonly used scenario for iterators in Python is the loop statement for, which encapsulates a collection with an iterator and cooks access to the collection elements to execute the loop.
For example:
for number in range(5):#range返回一个列表 print(number)
The range() returns a set containing the specified elements, and the for statement encapsulates it into an iterator and then accesses it. Using iter() can talk about lists, The collection is converted into an iterator, for example:
numbers=[1,2,3,4,5] #t就是迭代器 t=iter(numbers) #打印t对象,以便查看其类型 print(t)
Return result:
<list_iterator object at 0x10e805748>
Compared with ordinary Python objects, iterators have one more __next__()
method, each time Calling this method can return an element, and the caller (such as a for statement) can access the collection elements by continuously calling the __next__()
method.
For example:
numbers=[1,2,3,4,5] #t就是迭代器 t=iter(numbers) #打印t对象,以便查看其类型 print(t.__next__()) print(t.__next__()) print(t.__next__()) print(t.__next__())
Return result:
1 2 3 4
The caller can keep calling the __next__()
method until a StopIteration exception is returned.
Iterators are widely used in Python programming, so how do developers customize their own iterators?
The answer is to use the yield keyword.
Calling any function defined containing the yield keyword will not execute the function, but will obtain an iterator corresponding to the function.
Example:
import time def demoIternator(): print("---1---") yield 1 print("---2---") yield 2 print("---3---") yield 3 print("---4---") for x in demoIternator(): print(x) time.sleep(1)
Every time the __next__() method of the iterator is called, the iterator function will be executed and the result of yield will be returned as the iteration return element.
The above is the detailed content of Introduction to the Python keyword yield. For more information, please follow other related articles on the PHP Chinese website!