Python3.6 下yield的常见错误(AttributeError: 'generator' object has no attribute 'next')

来源:互联网 发布:手机理发软件 编辑:程序博客网 时间:2024/06/04 00:33

今天在python下写了协程的简单实现,但是竟然出现了错误,代码如下:

#-*- coding:utf-8 -*-import timedef 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 timedef 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)
阅读全文
0 0