Analysis of yield -Python3

Analysis of yield

First to a piece of code:

def fun1():
  for i in range(5):
    yield i
    print("继续调用继续执行")

gen1 = fun1()
print(gen1)

for i in gen1:
  print(i)

"""# 执行结果:
<generator object fun1 at 0x0365DEB0>
0
继续调用继续执行
1
继续调用继续执行
2
继续调用继续执行
3
继续调用继续执行
4
继续调用继续执行
"""

Directly result

  1. yield present in the body of the function generator is used to return the object, using a function generator is called the yield.
  2. Generator object iteration, for each iteration function will return the body to continue until there are no results
  3. Another next(迭代对象[, 默认参数])can be used to generate the iterator object, but each will get a result, many iterations to obtain all the results will be returned at the end of an abnormal [or default parameters].

Guess you like

Origin www.cnblogs.com/xust14521/p/11312028.html