python - 支持类的 .send() 吗?

标签 python class coroutine

写一个类,我怎么实现

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/

相关文章:

python - 正则表达式 - 替换除特定字符串之外的特定字符

用于生成字符串中可能的字符串替换的所有排列的 Python 模块?

javascript - 无法使用请求读取python Rest中的axios数据

python - 为什么我们需要 python 中的协程?

node.js - Promise.coroutine 如何支持生成器作为可屈服值?

python-3.x - 使用 next(gen) 和 gen.send(None) 启动 Python 3 生成器有区别吗?

python - 如何应用内核峰值为 1 的 3D 高斯滤波器?

Java:1.1:从该类创建类的实例。 1.2:实例化的线程化

php - PHP 类中的外部变量访问

python - 如何检查变量是否是类对象