写一个类,我怎么实现
foo.send(item) ?
__iter__
允许像生成器一样迭代类,如果我希望它成为协程怎么办?
最佳答案
这是一个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
方法的调用委托(delegate)给协程:
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.
关于python - 支持类的 .send() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4433886/