赞
踩
这个nonlocal是py3.x中才有的关键词
第一种情况,不使用nonlocal的情况:
- #-*- encoding:utf-8 -*-
- import sys
- reload(sys)
- sys.setdefaultencoding('utf-8')
- def test():
- x=1
- print("test="+str(x))
- #################################
- def test2():
- #nonlocal x
- x=3
- #################################
- print("test2="+str(x))
- test2()#这个的意思是在test()中测试使用test2()函数
-
- print x
- if __name__ == '__main__':
- test()

运行结果:
test=1
test2=3
1
[Finished in 0.0s]
- def test():
- x=1
- print("test:"+str(x))
- ##############################
- def test2():
- nonlocal x
- x=3
- print("test2:"+str(x))
- ##############################
- test2()
- print (x)
- if __name__ == '__main__':
- test()
test=1
test2=3
x= 3
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。