gpt4 book ai didi

Python-3.2 协程 : AttributeError: 'generator' object has no attribute 'next'

转载 作者:IT老高 更新时间:2023-10-28 20:31:19 25 4
gpt4 key购买 nike

引自 Python Essential Reference,David Beazley,第 20 页:

Normally, functions operate on a single set of input arguments. However, a function can also be written to operate as a task that processes a sequence of inputs sent to it. This type of function is known as a coroutine and is created by using the yield statement as an expression (yield) as shown in this example:

def print_matches(matchtext):
print "Looking for", matchtext
while True:
line = (yield) # Get a line of text
if matchtext in line:
print line

To use this function, you first call it, advance it to the first (yield), and then start sending data to it using send(). For example:

>>> matcher = print_matches("python")
>>> matcher.next() # Advance to the first (yield)
Looking for python
>>> matcher.send("Hello World")
>>> matcher.send("python is cool")
python is cool
>>> matcher.send("yow!")
>>> matcher.close() # Done with the matcher function call

根据这些信息,我编写了以下代码:

#!/usr/bin/python3.2
import sys

def match_text(pattern):
line = (yield)
if pattern in line:
print(line)

x = match_text('apple')
x.next()

for line in input('>>>> '):
if x.send(line):
print(line)

x.close()

但我收到如下错误消息:

Traceback (most recent call last):
File "xxx", line 9, in <module>
matcher.next() # Advance to the first (yield)
AttributeError: 'generator' object has no attribute 'next'

为什么这段代码(或者书中的代码,就此而言)在 Python 3.2 中不起作用?似乎应该是协程的东西被视为生成器 - 为什么?这是怎么回事?

最佳答案

你被错误信息吓跑了;在类型方面,Python 没有区别——你可以 .send 到任何使用 yield 的东西,即使它在内部没有对发送的值做任何事情。

在 3.x 中,不再附加 .next 方法;相反,使用内置的自由函数 next:

next(matcher)

关于Python-3.2 协程 : AttributeError: 'generator' object has no attribute 'next' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21622193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com