The function of yield in the function is similar to return. The difference is that the function does not exit after yield returns the result each time, but returns the result
Each time the yield keyword is encountered, the corresponding result is returned, and the current running state of the function is retained, waiting for the next call. If
A function needs to execute an action repeatedly, and the result of each execution is needed. This scenario is very suitable for using yield.
The function containing yield becomes a generator, which is also an iterator. It supports getting the next value through the next method.
Basic use of yield:
def func():
for i in range(0,3):
yield i
f = func()
f.next()
f.next()
For the generator, when the function next is called, the value of the expression after yield of the generator will be obtained;
When the yield statement ends after the last loop, the generator will throw stopiteration exception;
In addition to the next function, the generator also supports the send function. This function can pass parameters to the generator.
def func(n):
for i in range(0,n):
val = yield i
print val
f = func(10)
f.next()
#f.send(None)
f.send(2)
f.send(10)
print f.next()
Read More:
- Detailed explanation of yield in Python — the simplest and clearest explanation
- The usage of typing.union in Python
- In Python sys.argv Usage of
- Usage of Python dropout
- Usage of NVL in SQL
- Raise in Oracle_APPLICATION_Error Usage
- The usage and difference of atoi() and stoi() functions in C + +
- The function and usage of argc and argv in C language
- Usage of pause function in MATLAB
- Usage and examples of three important functions of tidyr package in R language: gather, spread and separate
- JS exception capture: the usage and example analysis of onerror() in window
- svn Key usage violation in certificate has been detected
- The usage of several integer functions in MATLAB (fix, floor, ceil, round)
- SSL handshake failed: SSL error: illegal key usage detected in the certificate
- Memory leak in Windows 8.1 with Killer E2200 and Windows Network Data Usage Monitoring
- On the usage of ‘ref.stor.type search’ field in SAP WM movement type
- On set in pandas_ Index and reset_ Usage of index
- Solve the problem of unable to locate package python3.6 when upgrading from python3.5 to python3.6 in ubantu16.04
- Principle and usage of feof ()
- Type definition error – one of the causes of type definition errors is WM in Oracle_ Concat function usage