今天在python下写了协程的简单实现,但是竟然出现了错误,代码如下:
#-*- coding:utf-8 -*-
import time
def A():
while True:
print('----A----')
yield
time.sleep(0.5)
def B(c):
print('----B----')
c.next()
time.sleep(0.5)
if __name__ == '__main__':
a = A()
B(a)
报错:
AttributeError: ‘generator’ object has no attribute ‘next’
后来查阅资料后知道了原因是在python 3.x中 generator(有yield关键字的函数则会被识别为generator函数)中的next变为next了,next是python3.x以前版本中的方法
修改为下面这样运行正常
#-*- coding:utf-8 -*-
import time
def A():
while True:
print('----A----')
yield
time.sleep(0.5)
def B(c):
print('----B----')
c.__next__()
time.sleep(0.5)
if __name__ == '__main__':
a = A()
print(a.__next__())
B(a)