python --yield 表达式的学习

def dog(name):
    print("道哥%s准备吃东西了"%name)
    while True:
        x=yield None #x拿到的是yield 接收到的值
        print("道哥%s吃了%s"%(name,x))
g=dog("alex")
print(g.__next__())
print(g.__next__())
g.send("一根骨头") # x="一根骨头"

/usr/local/bin/python3.8 /Users/futantan/PycharmProjects/S14/函数的学习/yield表达式.py
道哥alex准备吃东西了
None
道哥alex吃了None
None
道哥alex吃了一根骨头

 

 

2.

def dog(name):
    print("道哥%s准备吃东西了"%name)
    while True:
        x=yield #x拿到的是yield 接收到的值
        print("道哥%s吃了%s"%(name,x))
g=dog("alex")

g.send("一根骨头") # x="一根骨头"

/usr/local/bin/python3.8 /Users/futantan/PycharmProjects/S14/函数的学习/yield表达式.py
Traceback (most recent call last):
  File "/Users/futantan/PycharmProjects/S14/函数的学习/yield表达式.py", line 20, in <module>
    g.send("一根骨头") # x="一根骨头"
TypeError: can't send non-None value to a just-started generator

 

 

3.

def dog(name):
    print("道哥%s准备吃东西了"%name)
    while True:
        x=yield #x拿到的是yield 接收到的值
        print("道哥%s吃了%s"%(name,x))
g=dog("alex")
g.send(None) #等同于next(g)
等同于先挂在这个位置,然后下面执行给他一个参数
 g.send("一根骨头") # x="一根骨头"
g.send("啦啦")
g.close()
g.send("222")
/usr/local/bin/python3.8 /Users/futantan/PycharmProjects/S14/函数的学习/yield表达式.py
道哥alex准备吃东西了
道哥alex吃了一根骨头
道哥alex吃了啦啦

Traceback (most recent call last):
File "/Users/futantan/PycharmProjects/S14/函数的学习/yield表达式.py", line 23, in <module>
g.send("222")
StopIteration

 

 

 

4.

def dog(name):
    print("道哥%s准备吃东西了"%name)
    while True:
        x=yield 1111
        print("道哥%s吃了%s"%(name,x))
g=dog("alex")
res=g.send(None) #--->next(g)
print(res)
res1=g.send("一根骨头") # x="一根骨头"
print(res1)
g.send(['肉肉','瘦瘦'])
g.close()

/usr/local/bin/python3.8 /Users/futantan/PycharmProjects/S14/函数的学习/yield表达式.py
道哥alex准备吃东西了
1111
道哥alex吃了一根骨头
1111
道哥alex吃了['肉肉', '瘦瘦']

 

 

5.

def dog(name):
    food_list=[]
    print("道哥%s准备吃东西了"%name)
    while True:
        x=yield food_list
        print("道哥%s吃了%s"%(name,x))
        food_list.append(x)

g=dog("alex")
res=g.send(None) #--->next(g)
print(res)
res1=g.send("一根骨头") # x="一根骨头"
print(res1)
res3=g.send(['肉肉','瘦瘦'])
print(res3)
g.close()

/usr/local/bin/python3.8 /Users/futantan/PycharmProjects/S14/函数的学习/yield表达式.py
道哥alex准备吃东西了
[]
道哥alex吃了一根骨头
['一根骨头']
道哥alex吃了['肉肉', '瘦瘦']
['一根骨头', ['肉肉', '瘦瘦']]

 

 

 

posted @ 2020-12-17 21:04  正霜霜儿  阅读(85)  评论(0编辑  收藏  举报