Contrairement à une fonction normale, il semble se souvenir de la valeur renvoyée la dernière fois. Lorsqu'il est appelé, il renvoie la valeur suivante:
generator.py
def counter(num=10):
for _ in range(num):
yield 'run'
def greeting():
yield 'good morning'
yield 'good afternoon'
yield 'good night'
for g in greeting():
print(g)
g=greeting()
print(next(g)) #good morning
print(next(g)) #good afternoon
c=counter()
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
#print(next(c))J'obtiens une erreur
production:
good morning
good afternoon
good night
good morning
good afternoon
run
run
run
run
run
run
run
run
run
run
Recommended Posts