2010-12-13 43 views
6

寫作課,我該如何實施蟒蛇 - 支持.send()的類?

foo.send(item)?

__iter__允許迭代類像一個生成器,如果我想要它是一個協程?

+0

它沒有內置的Python像'__iter__'。 – 2010-12-13 22:01:06

+0

生成器和協程是Python中相同類型的對象。 – katrielalex 2010-12-13 22:23:02

回答

6

這裏是一個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行爲像一個協程(只要它有一個發送方法),但是是一個類 - 它可以有可以與協程交互的屬性和方法。

欲瞭解更多信息(和精彩實例),見大衛Beazley的Curious Course on Coroutines and Concurrency.

+0

我讀過比茲利的「好奇的課程」,並試圖實施一些我在那裏學到的東西,當我問這個問題時。感謝您展示def send(),我不確定這是否是採取的方法。 – 2010-12-14 06:33:15