python生成器浅析
A 'generator' is a function which returns a generator iterator. It looks like a normal function except that it contains yield expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the iterator's next() function.
The word 'generator' usually refers to a generator function, but may refer to a generator iterator in some contexts. In cases where the intended meaning isn't clear, using the full terms avoids ambiguity.
YIELD_VALUE pops top of stack (TOS) and yields it from a generator. Search(python dis documentation).
def p(x, end=' '): print(x, end=end) def gfn(): p(1); yield 21; p(2); yield 22; p(3); yield 23; print(gfn); print(gfn()); print(type(gfn())) for i in gfn(): p(i, '\n') import dis dis.dis(gfn) class Person: pass person = Person() print(type(person))
<function gfn at 0x000002136FB1E4C0>
<generator object gfn at 0x000002136FA9BBA0>
<class 'generator'>
1 21
2 22
3 23
3 0 LOAD_GLOBAL 0 (p)
2 LOAD_CONST 1 (1)
4 CALL_FUNCTION 1
6 POP_TOP
8 LOAD_CONST 2 (21)
10 YIELD_VALUE
12 POP_TOP
4 14 LOAD_GLOBAL 0 (p)
16 LOAD_CONST 3 (2)
18 CALL_FUNCTION 1
20 POP_TOP
22 LOAD_CONST 4 (22)
24 YIELD_VALUE
26 POP_TOP
5 28 LOAD_GLOBAL 0 (p)
30 LOAD_CONST 5 (3)
32 CALL_FUNCTION 1
34 POP_TOP
36 LOAD_CONST 6 (23)
38 YIELD_VALUE
40 POP_TOP
42 LOAD_CONST 0 (None)
44 RETURN_VALUE
<class '__main__.Person'>
C++: class Generator {
byte data[];
byte code[];
unsigned code_idx; // program counter, instruction pointer