python - Supporto Trasmettami () per una classe?
Domanda
Scrivi classe, come faccio a implementare
foo.send (voce)?
__iter__
iterazione consente sulla classe come un generatore, che cosa se voglio che sia una coroutine?
Soluzione
Ecco un esempio di base di un 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!
Possiamo fare una classe che contiene un tale coroutine, e invita delegati al suo metodo send
al coroutine:
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?')
Si noti che foo
agisce come un coroutine (nella misura in cui ha un metodo di invio), ma è una classe -. Può avere attributi e metodi che possono interagire con l'coroutine
Per ulteriori informazioni (ed esempi meravigliosi), vedi Corso curioso di David Beazley sulla coroutine e la concorrenza.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow