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

作者::Brad1994 时间:2023-08-01 13:11:10 

一、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 是对整个环境下的变量起作用,而不是对函数类的变量起作用。

来源:http://www.cnblogs.com/brad1994/p/6533267.html

标签:python,global关键字,nonlocal
0
投稿

猜你喜欢

  • 跟老齐学Python之网站的结构

    2021-08-22 05:55:54
  • python 函数中的参数类型

    2022-11-16 10:51:28
  • 企业网站该怎么做?

    2009-06-29 16:11:00
  • Django应用程序中如何发送电子邮件详解

    2023-11-04 02:07:54
  • pandas pd.cut()与pd.qcut()的具体实现

    2022-08-03 03:41:36
  • layer页面跳转,获取html子节点元素的值方法

    2024-04-29 13:43:15
  • python中 logging的使用详解

    2023-01-11 21:31:14
  • 如何通过python检查文件是否被占用

    2023-03-20 12:25:00
  • keras实现多种分类网络的方式

    2023-07-10 13:37:49
  • php下intval()和(int)转换使用与区别

    2023-06-11 14:09:54
  • django框架模板中定义变量(set variable in django template)的方法分析

    2021-11-18 03:28:04
  • asp如何在刷新链接之前验证文件是否存在?

    2010-06-22 21:09:00
  • 在pycharm中使用matplotlib.pyplot 绘图时报错的解决

    2021-05-22 10:37:31
  • Python3自定义http/https请求拦截mitmproxy脚本实例

    2021-04-13 15:33:01
  • python3代码输出嵌套式对象实例详解

    2021-09-16 07:35:55
  • 浏览器 cookie 限制

    2008-05-23 13:09:00
  • SQLite数据库管理相关命令的使用介绍

    2024-01-27 12:41:00
  • Python中的chr()函数与ord()函数解析

    2021-10-21 13:19:26
  • C#创建数据库及导入sql脚本的方法

    2024-01-23 04:08:04
  • 不要像HP一样考验客户的耐心

    2009-09-14 23:25:00
  • asp之家 网络编程 m.aspxhome.com