# Python 3.x中的nonlocal及其在2.x中的变通办法

by cnDenis http://cndenis.iteye.com 2012年12月26日

 ```1 2 3 4 5 6 7 8``` ```#!/usr/bin/python def outter(): x = 1 def inner(): print("inner is called, x=", x) return inner outter()() ```

 ```1 2 3 4 5 6 7 8 9``` ```#!/usr/bin/python def outter(): x = 1 def inner(): print("inner is called, x=", x) x = 2 return inner outter()() ```

 ``` 1 2 3 4 5 6 7 8 9 10``` ```#!/usr/bin/python def outter(): x = 1 def inner(): nonlocal x print("inner is called, x=", x) x = 2 return inner outter()() ```

 ``` 1 2 3 4 5 6 7 8 9 10``` ```#!/usr/bin/python def outter(): x = 1 def inner(): y = x print("inner is called, x=", y) y = 2 return inner outter()() ```

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15``` ```#!/usr/bin/python def outter(): x = 1 def inner(): nonlocal x print("inner is called, x=", x) x = 2 inner() print("outter after inner called, x=", x) outter() #Python 3.3中输出： #inner is called, x= 1 #outter after inner called, x= 2 ```

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14``` ```#!/usr/bin/python def outter(): x = {} x[0] = 1 def inner(): print("inner is called, x=", x[0]) x[0] = 2 inner() print("outter after inner called, x=", x[0]) outter() #Python 2.7中输出： #inner is called, x= 1 #outter after inner called, x= 2 ```

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17``` ```#!/usr/bin/python class C(object): pass def outter(): x = C() x.v = 1 def inner(): print("inner is called, x=", x.v) x.v = 2 inner() print("outter after inner called, x=", x.v) outter() #Python 2.7中输出： #inner is called, x= 1 #outter after inner called, x= 2 ```

Python 3.x中的nonlocal及其在2.x中的变通办法

• 0

开心

• 0

板砖

• 0

感动

• 0

有用

• 0

疑问

• 0

难过

• 0

无聊

• 0

震惊