# !/usr/bin/python3 def mygenerator (): value=yield 1 yield value return Donegen=mygenerator ()print(next (gen))print(Gen.send ( " I am Value "))
There is a method send inside the generator that can pass in a value again.
The above sentence may not understand, but it does not matter, we first look at the code,
#!/usr/bin/python3def MyGenerator(): value=yield 1 yield value return donegen=MyGenerator()print(next(gen))print(gen.send("I am Value"))
Code Analysis,
In Mygenerator, we used two yield altogether.
Oddly, the first yield statement, Value=yield 1. If you have not seen this statement, you certainly do not know that next back to yield, in fact, there is a value.
Here we go first, run the code first,
[penx@ali01 python]$ ./gen_send.py 1I am Value[penx@ali01 python]$
Run the process,
Start Generator Gen with next, knowing that yield 1 o'clock returns 1.
Then we use Gen's internal method of send into Gen, and bring back a value of "I am value". At this point, the code "value=" after yield 1 continues to be executed, assigning the returned value "I am Value" to value. Until the yield value is encountered, return the value.
In fact, send and next perform very much the same way, except that send can interact with the generator and pass in a value.
Generator startup requires next
Have you ever thought that if the generator has not been started, use send, what will happen? Let's try it out.
Code
#!/usr/bin/python3def MyGenerator(): value=yield 1 yield value return donegen=MyGenerator()print(gen.send(3))
Run
[penx@ali01 python]$ ./gen_send.py Traceback (most recent call last): File "./test.py", line 9, in <module> print(gen.send(3))TypeError: can‘t send non-None value to a just-started generator[[email protected] python]$
Results
Error
Typeerror:can ' t send non-none value to a just-started generator
It is said that the generator cannot send a value that is not none when it is started.
Summary
So, for the first time when we're using the generator, we're going to start with next.
Generator launches available send (None)
In fact, the above error has been said, can ' t send non-none value.
So, we can use Send (None) to start the generator.
Code
#!/usr/bin/python3def MyGenerator(): value=yield 1 yield value return donegen=MyGenerator()print(gen.send(None))print(gen.send(3))
Run
[penx@ali01 python]$ ./gen_send.py 13[penx@ali01 python
Results
Normal operation.
Python generator Send