【问题标题】:python - support .send() for a class?python - 支持 .send() 类?
【发布时间】:2010-12-13 21:56:44
【问题描述】:

写一个类,如何实现

foo.send(item) ?

__iter__ 允许像生成器一样对类进行迭代,如果我希望它成为协程怎么办?

【问题讨论】:

  • 它不像__iter__那样内置在Python中。
  • 生成器和协程在 Python 中是同一种对象。

标签: python class coroutine


【解决方案1】:

这是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.

【讨论】:

  • 我读过 beazley 的“好奇课程”,当我问这个问题时,我正在尝试实施我在那里学到的一些东西。感谢您展示 def send() ,我不确定这是否是采用的方法..
猜你喜欢
  • 1970-01-01
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 2019-01-31
  • 2018-09-24
相关资源
最近更新 更多