一个Future是用来表示将来要完成的结果,异步循环可以自动完成对这种对象的状态触发,例子如下:
import asyncio
def mark_done(future, result):
print('setting future result to {!r}'.format(result))
future.set_result(result)
event_loop = asyncio.get_event_loop()
try:
all_done = asyncio.Future()
print('scheduling mark_done')
event_loop.call_soon(mark_done, all_done, 'the result')
print('entering event loop')
result = event_loop.run_until_complete(all_done)
print('returned result: {!r}'.format(result))
finally:
print('closing event loop')
event_loop.close()
print('future result: {!r}'.format(all_done.result()))
输出结果如下:
scheduling mark_done
entering event loop
setting future result to 'the result'
returned result: 'the result'
closing event loop
future result: 'the result'
在这个例子里,并没有调用return语句,但也可以生成一个结果返回。Future的使用跟协程使用是一样的。
Python游戏开发入门
http://edu.csdn.net/course/detail/5690