当前位置:   article > 正文

nonlocal用法

nonlocal

这个nonlocal是py3.x中才有的关键词

第一种情况,不使用nonlocal的情况:

  1. #-*- encoding:utf-8 -*-
  2. import sys
  3. reload(sys)
  4. sys.setdefaultencoding('utf-8')
  5. def test():
  6. x=1
  7. print("test="+str(x))
  8. #################################
  9. def test2():
  10. #nonlocal x
  11. x=3
  12. #################################
  13. print("test2="+str(x))
  14. test2()#这个的意思是在test()中测试使用test2()函数
  15. print x
  16. if __name__ == '__main__':
  17. test()

运行结果:

test=1
test2=3
1
[Finished in 0.0s]

第二种,使用nonlocal的情况

  1. def test():
  2. x=1
  3. print("test:"+str(x))
  4. ##############################
  5. def test2():
  6. nonlocal x
  7. x=3
  8. print("test2:"+str(x))
  9. ##############################
  10. test2()
  11. print (x)
  12. if __name__ == '__main__':
  13. test()

运行结果:

test=1
test2=3
x= 3

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/854614?site
推荐阅读
相关标签
  

闽ICP备14008679号