笔记-python-变量作用域
笔记-python-变量作用域
1. python变量作用域和引用范围
1.1. 变量作用域
一般而言程序的变量并不是任何对象或在任何位置都可以访问的,访问权限决定于这个变量是在哪里赋值的。
变量的作用域决定了在哪一部分程序可以访问哪个变量。
Python的作用域一共有4种,分别是:
L (Local) 局部作用域
E (Enclosing) 闭包函数外的函数中
G (Global) 全局作用域
B (Built-in) 内建作用域
以 L –> E –> G –>B 的规则查找,即:在局部找不到,便会去局部外的局部找(例如闭包),再找不到就会去全局找,再者去内建中找。
Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如 if/elif/else/、try/except、for/while等)是不会引入新的作用域的,也就是说这这些语句内定义的变量,外部也可以访问,如下代码:
1.2. 全局变量和局部变量作用域
定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。
局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。如下实例:
# 全局变量和局部变量
total = 10
print(total, id(total))
def sum(arg1, arg2):
total = arg1 + arg2
print(total, id(total))
return total
c = sum(34, 12)
print(c, total, id(total))
输出:
10 1635020544
46 1635021696
46 10 1635020544
可以看出函数内外的total并非指向同一地址。
1.3. global and nonlocal
在函数内部是可以访问全局变量的,但有时需要在函数内部修改全局变量,又不想使用列表,这时,就要用到global 和nonlocal。
# global and nonlocal
num = 1
def fun1():
global num
print(num, id(num))
num = 123
print(num, id(num))
fun1()
print(num, id(num))
输出:
1 1635020256
123 1635024160
123 1635024160
可以发现变量num被修改,引用对象发生了变化。
如果要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字了,如下实例:
# nonlocal
def outer():
num = 10
print(num, id(num))
def inner():
nonlocal num
num = 100
print(num, id(num))
inner()
print(num, id(num))
outer()
输出:
10 1635020544
100 1635023424
100 1635023424
1.4. nonlocal
在python文档中对nonlocal的解释如下:
nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*
The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.
Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).
Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope.
需要注意的是nonlocal无法引用全局变量,下面的代码会报错,找不到num变量。
# nonlocal
num = 19
def outer():
#num = 10
print(num, id(num))
def inner():
nonlocal num
num = 100
print(num, id(num))
inner()
print(num, id(num))
outer()
2. 附
2.1. 一些报错的写法
有一种情况,假设下面这段代码被运行:
不讨论它是如何具体发生的,但显然,这样的写法引发了冲突,报错是正常的。
a = 10
def test():
a = a + 1
print(a)
test()
以上程序执行,报错信息如下:
……
a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment
错误信息为局部作用域引用错误,因为 test 函数中的 a 使用的是局部,未定义,无法修改。
下面是另一种类似错误:
a = 10
def fun1():
print(a)
a = 15
fun1()
输出:
print(a)
UnboundLocalError: local variable 'a' referenced before assignment
笔记-python-变量作用域的更多相关文章
- python变量作用域
[python变量作用域] 几个概念: python能够改变变量作用域的代码段是def.class.lamda. if/elif/else.try/except/finally.for/while 并 ...
- Python 变量作用域 LEGB (上)—— Local,Global,Builtin
Python 变量作用域的规则是 LEGB LEGB含义解释:L —— Local(function):函数内的名字空间E —— Enclosing function locals:外部嵌套函数的名字 ...
- Python 变量作用域与函数
Python 的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC语言的一种继承.Py ...
- Python 变量作用域 LEGB (下)—— Enclosing function locals
上篇:Python 变量作用域 LEGB (上)—— Local,Global,Builtin https://www.cnblogs.com/yvivid/p/python_LEGB_1.html ...
- Python 3 学习笔记之——变量作用域、模块和包
1. 变量作用域 Python 中,程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量是在哪里赋值的.变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称.Python 的作用域一共 ...
- python3学习笔记12(变量作用域)
变量作用域 参考http://www.runoob.com/python3/python3-function.html Python 中,程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量 ...
- python——变量作用域及嵌套作用域
----------------------------------------------------------------------------- 前言-------------------- ...
- python 变量作用域、闭包
先看一个问题: 下面代码输出的结果是0,换句话说,这个fucn2虽然已经用global声明了variable1,但还是没有改变变量的值 def func1(): variable1=0 def fun ...
- python变量作用域,函数与传参
一.元组传值: 一般情况下函数传递参数是1对1,这里x,y是2个参数,按道理要传2个参数,如果直接传递元祖,其实是传递一个参数 >>> def show( x, y ): ... p ...
- Python变量作用域(一)
在一个程序中使用变量名时,Python创建.改变或者查找变量名都是在所谓的命名空间中进行的.作用域指的就是命名空间. Python中的变量名在第一次赋值时已经创建,并且必须经过赋值后才能够使用.由于变 ...
随机推荐
- P1868 饥饿的奶牛
题目描述 有一条奶牛冲出了围栏,来到了一处圣地(对于奶牛来说),上面用牛语写着一段文字. 现用汉语翻译为: 有N个区间,每个区间x,y表示提供的x~y共y-x+1堆优质牧草.你可以选择任意区间但不能有 ...
- Elasticsearch在后台启动
Elasticsearch在linux下使用命令sh elasticsearch start,按键ctrl+c的时候程序就会stop掉,如何将程序在后台启动呢? 需要使用:./elasticsearc ...
- php允许被跨域ajax请求
只要在被请求端,加一句: header('Access-Control-Allow-Origin: *');
- 会话跟踪之Cookie
一:简介 Cookie主要用来存储用户信息,追踪用户会话.web客户端访问服务端直接采用的协议是Http,Http协议是一种无状态协议,无状态表现在不能够保留用户访问状态,无法记录用户信息.每一次的请 ...
- weex踩坑之旅第一弹 ~ 搭建具有入口文件的weex脚手架
写在前面的话: weex官方文档不完善,在整个实施过程中遇到过很多坑,中途几次想放弃,总是有些不甘心.攻坚克难,总也是会有一些收获,先将收获进行分享也或是记录,防止忘记.要想用好weex必须对es5/ ...
- 【Linux/Ubuntu学习 11】git查看某个文件的修改历史
有时候在比对代码时,看到某些改动,但不清楚这个改动的作者和原因,也不知道对应的BUG号,也就是说无从查到这些改动的具体原因了- [注]:某个文件的改动是有限次的,而且每次代码修改的提交都会有commi ...
- 使用kvm制作Eucalyptus镜像(Windows Server 2008r2为例)
1.前言 Elastic Utility Computing Architecture for Linking Your Programs To Useful Systems (Eucalyptus) ...
- 实战:ADFS3.0单点登录系列-集成SharePoint
这是本系列第四篇了,终于轮到SharePoint上场了,但是本文不会过多讲解SharePoint安装等话题,而是直入主题,讲解如何进行配置,让其于ADFS配合完成SSO的工作. 注意:本文使用的Sha ...
- 在 Visual Studio 或 SQLServer Management Studio 的代码编辑器中使用正则表达式匹配日期格式
使用正则查找时间格式文本 VS正则: (:z表示数字) ':z-:z-:z :z[\:]:z[\:]:z'
- 往ABAP gateway system上和Cloud Foundry上部署HTML5应用
ABAP Gateway system 在我的公众号文章里有详细介绍:SAP Fiori应用的三种部署方式 用WebIDE部署 用Eclipse Team provider部署 执行report /U ...