编写一个类,我该如何实现
foo.send(item)?
__iter__
允许像生成器一样遍历类,如果我想让它成为协程会怎么样?
答案 0 :(得分:7)
这是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
就像一个协程(只要它有一个send方法),但它是一个类 - 它可以有属性和方法,可以与协程进行交互。
有关更多信息(以及精彩示例),请参阅David Beazley的Curious Course on Coroutines and Concurrency.