笔记-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中的变量名在第一次赋值时已经创建,并且必须经过赋值后才能够使用.由于变 ...
随机推荐
- ADODB.Stream在进行文件上传时报错
最近在做web项目,有个控件是上传材料文件和文件夹,本地运行正常,放到服务器上,一直报错:AutoRuntime服务器无法创建..... 解决方法: 1.配置ie浏览器的安全级别 2.修改ie浏览器对 ...
- css中 repeat-x 的简单用法
问repeat-x 00 中: 0 0 是 什么意思,如果改为0 -50呢,不写话默认是什么(不写话和0 0 的效果不一样)- ------<html><head><s ...
- JavaSE_4_集合
1.Map和ConcurrentHashMap的区别? Map和ConcurrentHashMap的区别,Map是接口,ConcurrentHashMap是实现类 2.hashMap内部具体如何实现的 ...
- 【干货】JavaScript DOM编程艺术学习笔记4-6
四.案例研究:JavaScript图片库 js: function showPic(whichpic){ //取得链接 var source=whichpic.getAttribute("h ...
- 大数四则运算java(转)
// 大数的四则运算 #include <iostream> #include <string> #include <algorithm> using namesp ...
- SQL Server DBA SQL
. 监控事例的等待 ,,)) "Prev", ,,)) "Curr",count(*) "Tot" from v$session_Wait ...
- 汇编:jmp系列跳转指令总结
助记方法: J:跳转C: 进位位置位N: 否S: 符号位置位o: 溢出位置位Z: 零标志位置位E: 等于P:奇偶位置位A: AboveB: BelowL: Less (Little的比较级)G: Gr ...
- thinkphp 去掉URL 里面的index.php(?s=)
例如你的原路径是 http://localhost/test/index.php/home/goods/index.html 那么现在的地址是 http://localhost/test/home/g ...
- iphone 弹出键盘,文本框自动向上移动。
1.让类继承UITextViewDelegate UITextView *inputTextView;UIScrollView * _scrollView; 2.在init函数中先创建scrollVi ...
- slenium的xpath几种定位方式
练习地址,以下面地址为例: http://www.w3school.com.cn/example/xmle/books.xml 1. 查找book对象 //book #所有的数 //book[1] ...