def gen():
for i in range(1):
print('i=',i)
X = yield i
print('X=',X)
G = gen()
print('next(G)=',next(G))
print('next(G)=',next(G))
上面代码输出如下,可见如果等号的右边如果是 yield 语句,则等号左边的变量值默认是 None,除非用 send 语句对它赋值:
i= 0
next(G)= 0
X= None
Traceback (most recent call last):
File "c:\Users\rubin\AppData\Roaming\Code\User\rb\t.py", line 9, in
print('next(G)=',next(G))
StopIteration
但是对于下面的例子来说,即使没有用 send 语句,yield 返回的值也能赋值给等号左边的变量 reader 和 writer。
import asyncio
@asyncio.coroutine
def wget(host):
print('wget %s...' % host)
connect = asyncio.open_connection(host, 80)
reader, writer = yield from connect #yield 返回的值也能赋值给等号左边的变量
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
print('reader=%s write=%s' % (reader,writer))
writer.write(header.encode('utf-8'))
yield from writer.drain()
writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sohu.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
上面代码输出如下:
wget www.sohu.com. ..
reader=<StreamReader t=<_SelectorSocketTransport fd=592 read=polling write=<idle, bufsize=0>>> write=<StreamWriter transport=<_SelectorSocketTransport fd=592 read=polling write=<idle, bufsize=0>> reader=<StreamReader t=<_SelectorSocketTransport fd=592 read=polling write=<idle, bufsize=0>>>>
为何等号左边的变量 reader 和 writer 不是 None ?请问这是什么原理呢?谢谢!
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.