python - 为类支持 .send()?

7 投票
1 回答
3239 浏览
提问于 2025-04-16 08:29

在写一个类的时候,我该怎么实现

foo.send(item) 呢?

__iter__ 让这个类可以像生成器一样进行迭代,如果我想让它变成一个协程该怎么办呢?

1 个回答

7

这里有一个协程的基本示例

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方法),但其实它是一个类——它可以有属性和方法,这些属性和方法可以和协程进行交互。

想了解更多信息(还有很棒的示例),可以查看大卫·比兹利的关于协程和并发的有趣课程

撰写回答