码迷,mamicode.com
首页 > 编程语言 > 详细

python中global 和 nonlocal 的作用域

时间:2016-01-30 22:34:47      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:

python引用变量的顺序: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量 。

一 global

global关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字。

1 gcount = 0
2 
3 def global_test():
4     gcount+=1
5     print (gcount)
6 global_test()

D:\Python34\python.exe E:/PycharmProjects/Day3/globaltest.py
Traceback (most recent call last):
File "E:/PycharmProjects/Day3/globaltest.py", line 6, in <module>
global_test()
File "E:/PycharmProjects/Day3/globaltest.py", line 4, in global_test
gcount+=1
UnboundLocalError: local variable ‘gcount‘ referenced before assignment

Process finished with exit code 1

第一行定义了一个全局变量,(可以省略global关键字)。

在global_test 函数中程序会因为“如果内部函数有引用外部函数的同名变量或者全局变量,并且对这个变量有修改.那么python会认为它是一个局部变量,又因为函数中没有gcount的定义和赋值,所以报错。

 

二、声明全局变量,如果在局部要对全局变量修改,需要在局部也要先声明该全局变量:

gcount = 0

def global_test():
    global  gcount
    gcount+=1
    print (gcount)
global_test()

  如果在函数中声明 gcount 是全局变量,即可对其进行修改。 正确输出 1 。

 

三、 在局部如果不声明全局变量,并且不修改全局变量。则可以正常使用全局变量:

gcount = 0

def global_test():
    print (gcount)
global_test()

  如果在局部不修改全局变量,程序正确输出 0 。

 

四、nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。

def make_counter():  
    count = 0  
    def counter():  
        nonlocal count  
        count += 1  
        return count  
    return counter  
      
def make_counter_test():  
  mc = make_counter()  
  print(mc())
  print(mc())
  print(mc())

make_counter_test()

  输出:

   1

   2

   3

五、

def scope_test():
    def do_local():
        spam = "local spam" #此函数定义了另外的一个spam字符串变量,并且生命周期只在此函数内。此处的spam和外层的spam是两个变量,如果写出spam = spam + “local spam” 会报错
    def do_nonlocal():
        nonlocal  spam        #使用外层的spam变量
        spam = "nonlocal spam"
    def do_global():
        global spam
        spam = "global spam"
    spam = "test spam"
    do_local()
    print("After local assignmane:", spam)
    do_nonlocal()
    print("After nonlocal assignment:",spam)
    do_global()
    print("After global assignment:",spam)

scope_test()
print("In global scope:",spam)

  输出是:

After local assignmane: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

python中global 和 nonlocal 的作用域

标签:

原文地址:http://www.cnblogs.com/z360519549/p/5172020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!