One - One Code All

Blog Content

python关键字global和nonlocal的用法

Python   2017-01-25 22:46:26

一、global

global关键字用来在函数或其他局部作用域中使用全局变量。


1.1 如果局部要对全局变量修改,而不使用global关键字。

count = 0
def global_test():
    count += 1
    print(count)
global_test()

会出现如下错误:

UnboundLocalError: local variable 'count' referenced before assignment


1.2 如果局部要对全局变量修改,应在局部声明该全局变量。 

count = 0
def global_test():
    global count
    count += 1
    print(count)
global_test()

以上输出为:1

 注意:global会对原来的值(全局变量)进行相应的修改

count = 0
def global_test():
    global count
    count += 1
    print(count)
global_test()
print(count)

以上输出为:1,1


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

count = 0
def global_test():
    print(count)
global_test()

以上输出为:0


二、nonlocal

nonlocal声明的变量不是局部变量,也不是全局变量,而是外部嵌套函数内的变量。

def nonlocal_test():
    count = 0
    def test2():
        nonlocal count
        count += 1
        return count
    return test2
 
val = nonlocal_test()
print(val())
print(val())
print(val())


以上输出为:1,2,3



上一篇:Python判断字符串是否为字母或者数字(浮点数)
下一篇:pycodestyle (formerly called pep8) - Python style guide checker

The minute you think of giving up, think of the reason why you held on so long.