Python中关键字nonlocal和global的声明与解析

yipeiwu_com6年前Python基础

一、Python中global与nonlocal 声明

如下代码

a = 10 
 
def foo(): 
 a = 100 

执行foo() 结果 a 还是10

函数中对变量的赋值,变量始终绑定到该函数的局部命名空间,使用global 语句可以改变这种行为。

>>> a 
10 
>>> def foo(): 
...  global a 
...  a = 100 
... 
>>> a 
10 
>>> foo() 
>>> a 
100 

解析名称时首先检查局部作用域,然后由内而外一层层检查外部嵌套函数定义的作用域,如找不到搜索全局命令空间和内置命名空间。

尽管可以层层向外(上)查找变量,但是! ..python2 只支持最里层作用域(局部变量)和全局命令空间(gloabl),也就是说内部函数不能给定义在外部函数中的局部变量重新赋值,比如下面代码是不起作用的

def countdown(start): 
 n = start 
 def decrement(): 
  n -= 1 

python2 中,解决方法可以是是把修改值放到列表或字典中,python3 中,可以使用nonlocal 声明完成修改

def countdown(start): 
 n = start 
 def decrement(): 
  nonlocal n 
  n -= 1 

二、Python nonlocal 与 global 关键字解析

nonlocal

首先,要明确 nonlocal 关键字是定义在闭包里面的。请看以下代码:

x = 0
def outer():
 x = 1
 def inner():
  x = 2
  print("inner:", x)

 inner()
 print("outer:", x)

outer()
print("global:", x)

结果

# inner: 2
# outer: 1
# global: 0

现在,在闭包里面加入nonlocal关键字进行声明:

x = 0
def outer():
 x = 1
 def inner():
  nonlocal x
  x = 2
  print("inner:", x)

 inner()
 print("outer:", x)

outer()
print("global:", x)

结果

# inner: 2
# outer: 2
# global: 0

看到区别了么?这是一个函数里面再嵌套了一个函数。当使用 nonlocal 时,就声明了该变量不只在嵌套函数inner()里面
才有效, 而是在整个大函数里面都有效。

global

还是一样,看一个例子:

x = 0
def outer():
 x = 1
 def inner():
  global x
  x = 2
  print("inner:", x)

 inner()
 print("outer:", x)

outer()
print("global:", x)

结果

# inner: 2
# outer: 1
# global: 2

global 是对整个环境下的变量起作用,而不是对函数类的变量起作用。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

Python读写文件基础知识点

Python读写文件基础知识点

在 Python 中,读写文件有 3 个步骤:  1.调用 open()函数,返回一个 File 对象。  2.调用 File 对象的 read()或 write()...

python的mysqldb安装步骤详解

python的mysqldb安装步骤详解 安装MySQLdb: 一、 什么是MySQLdb? 解释:MySQLdb是Python操作MySQL的一个接口包。这里要理解一个概念,pytho...

Python3.6连接Oracle数据库的方法详解

本文实例讲述了Python3.6连接Oracle数据库的方法。分享给大家供大家参考,具体如下: 下载cx_Oracle模块模块: https://pypi.python.org/pypi...

基于python元祖与字典与集合的粗浅认识

一,元祖(tuple) 1.元祖是不能修改的,通常写成圆括号中的一系列项,位置有序,固定长度 2.实际上元祖支持字符串和列表的一般序列操作,“+”,“*”以及分片操作应用于元祖时会返回新...

Python随机生成一个6位的验证码代码分享

1. 生成源码 复制代码 代码如下: # -*- coding: utf-8 -*- import random def generate_verification_code(): &n...