美文网首页Py100Skills
[Py006] global vs nonlocal

[Py006] global vs nonlocal

作者: 安哥生个信 | 来源:发表于2018-10-18 12:19 被阅读7次

    可参考https://www.cnblogs.com/brad1994/p/6533267.html

    global 只能作用于全局环境,针对的是最外层的 x=0

    外层函数outer 下的x=1 无法被 global 覆盖,所以最后print("outer:",x) 返回的是1

    In[2]: x = 0 
    In[3]: def outer():
      ...:     x = 1
      ...:     def inner():
      ...:         global x
      ...:         x = 2
      ...:         print("inner:",x)
      ...:     inner()
      ...:     print("outer:",x)
      ...:     
    In[4]: outer()
    inner: 2
    outer: 1
    In[5]: print("global:",x)
    global: 2
    

    nonlocal 只能在闭包里面使用

    当使用 nonlocal 时候,就声明了x 不知在嵌套函数inner 里有效,而是在整个大函数outer里面都有效

    In[6]: def outer():
      ...:     x = 1
      ...:     def inner():
      ...:         nonlocal x
      ...:         x = 2
      ...:         print("inner:",x)
      ...:     inner()
      ...:     print("outer:",x)
      ...:     
    In[7]: x=0
    In[8]: outer()
    inner: 2
    outer: 2
    In[9]: print("global:",x)
    global: 0
    

    相关文章

      网友评论

        本文标题:[Py006] global vs nonlocal

        本文链接:https://www.haomeiwen.com/subject/skbjzftx.html