#!/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()

这是一个合作项目,但不是Python .2将其视为发电机——为什么?这是怎么回事?我指的是David Beazeley的《Python基本参考》,第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

为什么我的代码不起作用-DB不起作用..

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'

推荐答案

你被错误信息吓跑了;就类型而言,Python没有区别——使用yield的任何东西都可以使用.send,即使它在内部不处理发送的值.

3.x、 这些方法不再附带.next种方法;相反,使用内置的免费功能next:

next(matcher)

Python-3.x相关问答推荐

是什么原因导致Pandas=2.1.4和Pandas=1.4.2之间Pandas DataFrame中从Float64到int32的连续列转换方式不同

如何使用魔杖扭曲图像

合并所有文件并获取特定列数据

如何将 WebDriver 传输到导入的测试?

try 使用 GEKKO 求解非线性方程组.系统有多种解决方案,但 GEKKO 给出了错误的解决方案.我该如何解决?

有没有一种方法可以通过输入从 0 到 255 的 R、G 和 B 值来生成 RGB colored颜色 ,而无需使用 python 中的 matplotlib 模块?

如何使用复选按钮更改 Pyplot 轴的属性?

通过点和线计算CV2 Homography

spaCy 中的匹配模式返回空结果

判断对 python 3 支持的要求

通过多个键对字典列表进行分组和聚合

如何遍历某些扩展名的文件?

类方法和实例方法同名

使用完整路径激活 conda 环境

matplotlib - 模块sip没有属性setapi

连接 dict 值,它们是列表

带有自定义标头的 urllib.urlretrieve

哪个更有效:Python 文档字符串还是类型提示?

什么是ANSI_X3.4-1968编码?

在 Ipython 中使用 Pylint (Jupyter-Notebook)