WithyieldFunction, is a special iterator, containsGenerator functionwithGenerator expression(as an expression of (elem for elem in [1, 2, 3]))
#
# Input: 1. 5-->5 2. 3 --->8 3. 2--->10 4. 2---->12
# Output: 1. 5 2. 4 3. 3.333 4. 3
def avg():
num = 0
total = 0.0
#
while 1:
#
val = yield
#Calculation +1
num += 1
total += val
# is equal to the total / calculation times
avg = total/num
Print('current average{}'.format(avg))
counter = avg()
counter.send(None)
while True:
Num = input('Please enter a number:')
num = float(num)
counter.send(num)
from inspect import getgeneratorstate
def simple_gen1():
print('started')
x = yield 'running'
print('receive_x:',x)
y = yield x
print('receive_y:', y)
test1 = simple_gen1()
print(getgeneratorstate(test1))
next(test1)
print(getgeneratorstate(test1))
next(test1)
print(getgeneratorstate(test1))
try:
next(test1)
except Exception:
pass
print(getgeneratorstate(test1))
##output:
GEN_CREATED
started
GEN_SUSPENDED
receive_x: None
GEN_SUSPENDED
receive_y: None
GEN_CLOSED
From the above code, we can see that the generator is stateful -> not activated, paused, has ended
The coroutine is a lightweight thread that implements task switching in a single thread. His scheduling does not require a 'stunning' operating system, and the switching overhead between tasks is smal...
Coroutine Coroutine, also known as micro-threading, fiber. English name Coroutine. The coroutine is Coroutine is another implementation in pythonMultitaskingThe way it is just smaller than the thread ...
Generator generator Before discussing the coroutine, let's take a look at python.Builder. In simple terms, in Python, the mechanism of computing while looping is calledBuilder. for example. Generating...
Coroutine Coroutines, also known as micro-threads, coroutines are lightweight threads A user state (operating system simply does not know of his existence, is the user's own control) is a coroutine fu...
Coroutine, also called micro-threads, shred. English Coroutine. Subroutine or function is called, is a call hierarchy in all languages, such as A calls B, B in the implementation process and called C,...
The difference between generator and coroutine The usage of yield in Python is very similar to return, both of which provide a return value, but the biggest difference between yield and return is that...
Iterator Iteration is a way to access collection elements. An iterator is an object that can remember the position of traversal. The iterator object is accessed from the first element of the collectio...
Just introduced the pythonyield keyword, strike while the iron is hot, now let's learn about the yield implementation of the coroutine. To quote the official statement: γγ Compared with threads, corou...
yield Such as: Because yield can suspend the execution of the function, it can also re-execute the particularity of the function, which can realize the coroutine First get all the functions, that is, ...