def chicken(): print('=====>first') yield 1 print('=====>sencond') yield 2 print('=====>third') yield 3 obj=chicken() print(obj) # <generator object chicken at 0x000002CEE1A7AAC8> 是一个生成器, 一只老母鸡
print(obj.__iter__() is obj) # True print(next(obj)) # =====>first 1 print(next(obj)) # =====>sencond 2 print(next(obj)) # =====>third 3
for item in obj: print(item) ''' =====>first 1 =====>sencond 2 =====>third 3 ''' ------------------------------------------------------------ 🍔一、"iter_obj=obj.__iter__()" 拿到迭代器 🍔二、触发 "iter_obj.__next__()" 拿到该方法的返回值,赋值给item 🍔三、周而复始,直到函数内不在有 "yield", 即取值完毕 🍔四、"for" 会检测到 "StopIteration" 异常,结束循环
def my_range(): n = 0 while True: yield n n += 1 obj = my_range() # 一个生成器 print(obj) # <generator object my_range at 0x0000022784809F48>输出的是老母鸡内存地址 🍔使用"next"取值 print(next(obj)) # 0 print(next(obj)) # 1 print(next(obj)) # 2 print(next(obj)) # 3 ......等等.. 🍔使用 "for" 循环 for i in my_range(): # 也能够使用 for 循环取 print(i)
def my_range(start, stop, step = 1): n = start while n < stop: yield n n += step 🍔使用 "next" 取值 obj = my_range(2 ,14, 2) print(next(obj)) # 2 print(next(obj)) # 4 print(next(obj)) # 6 🍔使用 "for" 循环 for line in my_range(2, 15, 3) print(line)
next
: 执行一次python
send
: send 会传送一个值给 yield 关键字, 赋值给 yield 左边的的变量名, 再执行等同于 next 的功能继续执行下面的代码函数
close
: 当使用 close 时, 会关闭生成器, 没法在进行迭代取值, 取值则报 StopIteration 异常code
喂狗示例: ps : "dog.send(None)" 的效果等于 "next(dog)"协程
def eat(name): print('%s start eat' %name) while True: food = yield 1 # yield 接收 send 传过来的值赋值给 food print('%s start eat %s'%(name,food)) dog = eat('派大星的狗') # 得到生成器 next(dog) # 派大星的狗 start eat dog.send("海绵宝宝") # 派大星的狗 start eat 海绵宝宝 (send 自带 next 的执行功能) dog.close() # 关闭这个生产器 (没法在进行取值) next(dog) # 再次取值跑出异常 "StopIteration"