#!/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()
Run Code Online (Sandbox Code Playgroud)
这是一个协程,但Python3.2将其视为生成器 - 为什么?这里发生了什么?我指的是David Beazeley编写的Python Essential Reference: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 …Run Code Online (Sandbox Code Playgroud)