首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python-3.2协程: AttributeError:'generator‘对象没有'next’属性

Python-3.2协程: AttributeError:'generator‘对象没有'next’属性
EN

Stack Overflow用户
提问于 2014-02-07 15:54:14
回答 2查看 56.4K关注 0票数 37
代码语言:javascript
复制
#!/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()

这是一个协程,但Python3.2将其视为生成器-为什么?这里发生什么事情?我指的是David Beazeley pg:20的Python Essential Reference。

引用相关章节:

代码语言:javascript
复制
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

为什么我的代码不能工作--数据库不能工作..

代码语言:javascript
复制
deathstar> python3.2 xxx   
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'
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-07 16:25:12

您被错误消息搞糊涂了;就类型而言,Python不做任何区分--您可以对任何使用yield的内容执行.send操作,即使它不会在内部对发送的值做任何操作。

在3.x中,这些函数不再附加.next方法;取而代之的是使用内置的自由函数next

代码语言:javascript
复制
next(matcher)
票数 63
EN

Stack Overflow用户

发布于 2017-10-25 20:42:34

对于Python3.2版,next()内置函数的语法应该是matcher.__next__()next(matcher)

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21622193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档