|
发表于 2017-1-25 14:48:06
|
显示全部楼层
回帖奖励 +1 鱼币
- >>> def funx():
- x = 5
- def funy(x):
- x *= x
- return x
- return funy(x)
- >>> import dis
- >>> dis.dis(funx)
- 2 0 LOAD_CONST 1 (5)
- 3 STORE_FAST 0 (x)
- 3 6 LOAD_CONST 2 (<code object funy at 0x019CBC50, file "<pyshell#1>", line 3>)
- 9 LOAD_CONST 3 ('funx.<locals>.funy')
- 12 MAKE_FUNCTION 0
- 15 STORE_FAST 1 (funy)
- 6 18 LOAD_FAST 1 (funy)
- 21 LOAD_FAST 0 (x)
- 24 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
- 27 RETURN_VALUE
- >>> def funq():
- x = 5
- def funp():
- nonlocal x
- x *= x
- return x
- return funp
- >>> dis.dis(funq)
- 2 0 LOAD_CONST 1 (5)
- 3 STORE_DEREF 0 (x)
- 3 6 LOAD_CLOSURE 0 (x)
- 9 BUILD_TUPLE 1
- 12 LOAD_CONST 2 (<code object funp at 0x019B27F0, file "<pyshell#5>", line 3>)
- 15 LOAD_CONST 3 ('funq.<locals>.funp')
- 18 MAKE_CLOSURE 0
- 21 STORE_FAST 0 (funp)
- 7 24 LOAD_FAST 0 (funp)
- 27 RETURN_VALUE
- >>>
复制代码
LOAD_CLOSURE
MAKE_CLOSURE
这两个是构造闭包的指令。
自己看,仔细体会
严格按照闭包的语法格式书写。 |
|