【发布时间】:2010-12-13 21:56:44
【问题描述】:
写一个类,如何实现
foo.send(item) ?
__iter__ 允许像生成器一样对类进行迭代,如果我希望它成为协程怎么办?
【问题讨论】:
-
它不像
__iter__那样内置在Python中。 -
生成器和协程在 Python 中是同一种对象。
写一个类,如何实现
foo.send(item) ?
__iter__ 允许像生成器一样对类进行迭代,如果我希望它成为协程怎么办?
【问题讨论】:
__iter__那样内置在Python中。
这是basic example of a coroutine:
def coroutine(func):
def start(*args,**kwargs):
cr = func(*args,**kwargs)
cr.next()
return cr
return start
@coroutine
def grep(pattern):
print "Looking for %s" % pattern
while True:
line = (yield)
if pattern in line:
print(line)
g = grep("python")
# Notice how you don't need a next() call here
g.send("Yeah, but no, but yeah, but no")
g.send("A series of tubes")
g.send("python generators rock!")
# Looking for python
# python generators rock!
我们可以创建一个包含这样一个协程的类,并将对其send方法的调用委托给协程:
class Foo(object):
def __init__(self,pattern):
self.count=1
self.pattern=pattern
self.grep=self._grep()
@coroutine
def _grep(self):
while True:
line = (yield)
if self.pattern in line:
print(self.count, line)
self.count+=1
def send(self,arg):
self.grep.send(arg)
foo = Foo("python")
foo.send("Yeah, but no, but yeah, but no")
foo.send("A series of tubes")
foo.send("python generators rock!")
foo.pattern='spam'
foo.send("Some cheese?")
foo.send("More spam?")
# (1, 'python generators rock!')
# (2, 'More spam?')
请注意,foo 的行为类似于协程(只要它具有发送方法),但它是一个类——它可以具有可以与协程交互的属性和方法。
有关更多信息(和精彩示例),请参阅 David Beazley 的Curious Course on Coroutines and Concurrency.
【讨论】: