No puedo entender el método send
. Entiendo que se usa para operar el generador. Pero la sintaxis está aquí: generator.send(value)
.Python 3: enviar método de generadores
que de alguna manera no se puede coger por qué el valor debe ser el resultado de la corriente yield
expresión. Preparé un ejemplo:
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')
El resultado es:
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
Bueno, francamente, se me asombroso.
- En la documentación se puede leer que cuando se ejecuta una instrucción
yield
, el estado del generador se congela y el valor deexpression_list
se devuelve a la persona que llamanext
‘s. Bueno, parece que no ha sucedido. ¿Por qué podemos ejecutar la declaraciónif
y la funciónprint
dentro degen()
? - ¿Cómo puedo entender por qué
X
dentro y fuera de la función es diferente? Ok. Supongamos quesend(77)
transmite 77 enm
. Bueno, la expresiónyield
se convierte en 77. Entonces, ¿qué esX = yield i
? ¿Y cómo 77 dentro de la función se convierte en 5 cuando ocurre afuera? - ¿Por qué la primera cadena de resultados no refleja nada de lo que sucede dentro del generador?
De todos modos, ¿podría usted de alguna manera comentar estas declaraciones send
y yield
?
se ejecuta al mismo tiempo pero no en paralelo. – jfs
@ J.F.Sebastian Creo que "concurrentemente" significa en paralelo? – ecatmur
en la programación "paralelo" implica "concurrente" pero lo opuesto en general no es cierto. [Diferencia entre programación simultánea y programación paralela] (http://stackoverflow.com/q/1897993/4279) – jfs