python 变量作用域

电玩女神 2022-10-01 03:57 343阅读 0赞

几个概念:

  • python能够改变变量作用域的代码段是def、class、lamda.
  • if/elif/else、try/except/finally、for/while 并不能涉及变量作用域的更改,也就是说他们的代码块中的变量,在外部也是可以访问的
  • 变量搜索路径是:本地变量->全局变量
  • python能够改变变量作用域的代码段是def、class、lamda.

    def scopetest():

    1. localvar=6;
    2. print(localvar)

    scopetest()

    print(localvar) #去除注释这里会报错,因为localvar是本地变量

  • if/elif/else、try/except/finally、for/while

    while True:

    1. newvar=8
    2. print(newvar)
    3. break;

    print(newvar)

    try:

    1. newlocal=7
    2. raise Exception

    except:

    1. print(newlocal)#可以直接使用哦

输出结果:8 8 7

可见这个关键字中定义变量,他们的作用域跟外部是一致的,这个跟Java的作用域概念有点不一样。

  • 变量搜索路径是:本地变量->全局变量

    def scopetest():

    1. var=6;
    2. print(var)#

    var=5
    print(var)
    scopetest()
    print(var)

输出结果:5 6 5

这里var 首先搜索的是本地变量,scopetest()中 var=6相当于自己定义了一个局部变量,赋值为6. 当然如果的确要修改全局变量的值,则需要如下:

  1. def scopetest():
  2. global var
  3. var=6;
  4. print(var)#
  5. var=5
  6. print(var)
  7. scopetest()
  8. print(var)

输出结果:5 6 6

再看一种这种情况:

  1. def scopetest():
  2. var=6;
  3. print(var)#
  4. def innerFunc():
  5. print(var)#look here
  6. innerFunc()
  7. var=5
  8. print(var)
  9. scopetest()
  10. print(var)

输出结果:5 6 6 5
根据调用顺序反向搜索,先本地变量再全局变量,例如搜先在innerFunc中搜索本地变量,没有,好吧,找找调用关系上一级scopetest,发现本地变量var=6,OK,就用他了。

发表评论

表情:
评论列表 (有 0 条评论,343人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Python变量作用

    Python程序有各种各样的命名空间,它指的是在该程序段内一个特定的名称是独一无二的,它和其它同名的命名空间是无关的。 在Python中每一个函数都有自己的命名空间,如果在函