zoukankan      html  css  js  c++  java
  • 函数的作用域

     1 x=int(2.9)    #int built-in
     2 g_count = 0   #global
     3 def outer():
     4     o_count = 1   #inclosing
     5     def inner():
     6         i_count = 2    #local
     7         print(i_count)
     8     inner()
     9 outer()
    10 
    11 
    12 count = 10   #全局变量,在局部作用域里不能修改
    13 
    14 def outer():
    15     global count
    16 
    17     print(count)     #局部作用域不能修改全局变量的值
    18     count = 5
    19     print(count)
    20 
    21 outer()
    22 
    23 
    24 
    25 
    26 def outer():
    27     count = 10               #局部变量
    28     def inner():
    29         nonlocal count       #nonlocal  关键字 ,配合修改变量
    30         count = 20
    31         print(count)
    32     inner()
    33     print(count)
    34 outer()

    小结:

    (1)变量查找顺序:LEGB,作用域局部>外层作用域>当前模块中的全局>python内置作用域;

    (2)只有模块/类/函数才能引入新作用域;

    (3)对于一个变量,内部作用域先声明就会覆盖外部变量,不声明直接使用,就会使用外部作用于的变量;

    (4)内部作用域要修改外部作用域变量的值时,全局变量要使用global关键字,嵌套作用域变量使用nonlocal关键字。nonlocal时pyython3新增的关键字,有了这个关键字,就能完美的实现闭包了。

  • 相关阅读:
    11
    不错的Spring学习笔记(转)
    面相对象
    Shiro框架学习
    浅谈重载与重写
    二叉树的Java实现及特点总结
    Spring注解及作用
    java中String与StringBuilder的区别
    Java String, StringBuffer和StringBuilder实例
    Docker Mysql主从同步配置搭建
  • 原文地址:https://www.cnblogs.com/hui147258/p/11047968.html
Copyright © 2011-2022 走看看