Non riesco a capire il metodo send
. Capisco che è usato per far funzionare il generatore. Ma la sintassi è qui: generator.send(value)
.Python 3: metodo di invio dei generatori
In qualche modo non riesco a capire perché il valore dovrebbe diventare il risultato dell'attuale espressione yield
. Ho preparato un esempio:
def gen():
for i in range(10):
X = yield i
if X == 'stop':
break
print("Inside the function " + str(X))
m = gen()
print("1 Outside the function " + str(next(m)) + '\n')
print("2 Outside the function " + str(next(m)) + '\n')
print("3 Outside the function " + str(next(m)) + '\n')
print("4 Outside the function " + str(next(m)) + '\n')
print('\n')
print("Outside the function " + str(m.send(None)) + '\n') # Start generator
print("Outside the function " + str(m.send(77)) + '\n')
print("Outside the function " + str(m.send(88)) + '\n')
#print("Outside the function " + str(m.send('stop')) + '\n')
print("Outside the function " + str(m.send(99)) + '\n')
print("Outside the function " + str(m.send(None)) + '\n')
Il risultato è:
1 Outside the function 0
Inside the function None
2 Outside the function 1
Inside the function None
3 Outside the function 2
Inside the function None
4 Outside the function 3
Inside the function None
Outside the function 4
Inside the function 77
Outside the function 5
Inside the function 88
Outside the function 6
Inside the function 99
Outside the function 7
Inside the function None
Outside the function 8
Beh, francamente, mi è sorprendente.
- Nella documentazione si legge che quando viene eseguita una dichiarazione
yield
, lo stato del generatore è congelato e il valore diexpression_list
viene restituito al chiamantenext
s’. Beh, non sembra che sia successo. Perché è possibile eseguire l'istruzioneif
e la funzioneprint
all'interno digen()
. - Come posso capire perché lo standard
X
all'interno e all'esterno della funzione è diverso? Ok. Supponiamo chesend(77)
trasmetta 77 am
. Bene, l'espressioneyield
diventa 77. Allora cos'èX = yield i
? E come la funzione 77 si converte in 5 quando si verifica all'esterno? - Perché la prima stringa del risultato non riflette nulla che sta succedendo all'interno del generatore?
In ogni caso, potresti commentare in qualche modo queste dichiarazioni send
e yield
?
semplicemente non viene eseguito contemporaneamente in parallelo. – jfs
@ J.F.Sebastian Penso che "simultaneamente" significhi in parallelo? – ecatmur
in programmazione "parallelo" implica "concurrent", ma il contrario in generale non è vero. [Differenza tra programmazione simultanea e programmazione parallela] (http://stackoverflow.com/q/1897993/4279) – jfs