Python - 变量的作用域
变量作用域
- Python能够改变变量作用域的代码段是 def 、 class 、 lamda.
- if/elif/else、try/except/finally、for/while 并不能涉及变量作用域的更改,也就是说他们的代码块中的变量,在外部也是可以访问的
- 变量搜索路径是:局部变量->全局变量
局部变量vs全局变量
局部变量:在函数内部,类内部,lamda.的变量,它的作用域仅在函数、类、lamda里面
全局变量:在当前py文件都生效的变量
global的作用
让局部变量变成全局变量
def tests():
global vars
vars = 6 tests()
print(vars)
执行结果
6
切记
先global声明一个变量,再给这个变量赋值,不能直接 global vars = 6 ,会报错哦!!
if/elif/else、try/except/finally、for/while
# while
while True:
var = 100
break
print(var) # try except
try:
var = 111
raise Exception
except:
print(var) print(var) # if
if True:
var = 222 print(var) # elif
if False:
pass
elif True:
var = 333
print(var) # else
if False:
pass
else:
var = 444
print(var) # for
for i in range(0, 1):
var = 555 print(var)
执行结果
100
111
111
222
333
444
555
变量搜索路径是:局部变量->全局变量
def test():
var = 6
print(var) # var = 5
print(var)
test()
print(var)
执行结果
5
6
5
Python的LEGB规则
- L-Local(function);函数内的变量
- E-Enclosing function locals;外部嵌套函数的变量
- G-Global(module);函数定义所在模块的变量
- B-Builtin(Python);Python内建函数的名字空间
这是我们代码找变量的顺序,倘若最后一个python内建函数也没有找到的话就会报错了
什么是内建函数呢?
无需安装第三方库,可以直接调用的函数,让我们来看看有哪些内建函数:
print(dir(__builtins__))
执行结果
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
看LEGB的栗子
# Python内建函数的变量
x = int(0.22) # 全局变量
x = 1 def foo():
# 外部函数变量
x = 2 def innerfoo():
# 局部变量
x = 3
print('local ', x) innerfoo()
print('enclosing function locals ', x) foo()
print('global ', x)
执行结果
local 3
enclosing function locals 2
global 1
当我们改动下代码,把局部变量注释
# Python内建函数的变量
x = int(0.22) # 全局变量
x = 1 def foo():
# 外部函数变量
x = 2 def innerfoo():
# 局部变量
# x = 3 ##### 被注释掉了
print('local ', x) innerfoo()
print('enclosing function locals ', x) foo()
print('global ', x)
执行结果
local 2
enclosing function locals 2
global 1
现在把外部函数变量也注释掉
# Python内建函数的变量
x = int(0.22) # 全局变量
x = 1 def foo():
# 外部函数变量
# x = 2 ###注释 def innerfoo():
# 局部变量
# x = 3 ###注释
print('local ', x) innerfoo()
print('enclosing function locals ', x) foo()
print('global ', x)
执行结果
local 1
enclosing function locals 1
global 1
现在把全局变量也注释掉
# Python内建函数的变量
x = int(0.22) # 全局变量
# x = 1 def foo():
# 外部函数变量
# x = 2 def innerfoo():
# 局部变量
#x = 3
print('local ', x) innerfoo()
print('enclosing function locals ', x) foo()
print('global ', x)
执行结果
local 0
enclosing function locals 0
global 0
注意点
其实一般不会用到外部嵌套函数的作用域,所以只要记得Python内建函数作用域 > 全局变量作用域 > 局部变量作用域就好了
Python - 变量的作用域的更多相关文章
- Python变量的作用域在编译过程中确定
为了节省读友的时间,先上结论(对于过程和细节感兴趣的读友可以继续往下阅读,一探究竟): [结论] 1)Python并不是传统意义上的逐行解释型的脚本语言 2)Python变量的作用域在编译过程就已经确 ...
- Python——变量的作用域
原创声明:本文系博主原创文章,转载及引用请注明出处. 1. 在编程语言中,变量都有一定的作用域,用来限定其生命周期,且不同类型的变量作用域不同. 在Python中解释器引用变量的顺序(优先级)为:当前 ...
- 『无为则无心』Python函数 — 30、Python变量的作用域
目录 1.作用于的概念 2.局部变量 3.全局变量 4.变量的查找 5.作用域中可变数据类型变量 6.多函数程序执行流程 1.作用于的概念 变量作用域指的是变量生效的范围,在Python中一共有两种作 ...
- Python变量的作用域
局部变量 局部变量是指在函数内部定义并使用的变量,他只在函数内部有效.即函数内部的名字只在函数运行时才会创建,在函数运行之前或者运行完毕之后,所有的名字就都不存在了.所以,如果在函数外部使用函数内部定 ...
- python中对变量的作用域LEGB、闭包、装饰器基本理解
一.作用域 在Python程序中创建.改变.查找变量名时,都是在一个保存变量名的空间中进行,我们称之为命名空间,也被称之为作用域.python的作用域是静态的,在源代码中变量名被赋值的位置决定了该变量 ...
- Python学习之变量的作用域
学习地址:http://www.jianshu.com/p/17a9d8584530 1.变量作用域LEGB 1.1变量的作用域 在Python程序中创建.改变.查找变量名时,都是在一个保存变量名的空 ...
- python命名空间、作用域、闭包与传值传引用
(以下内容,均基于python3) 最近在看python函数部分,讲到了python的作用域问题,然后又讲了Python的闭包问题. 在做作业的时候,我遇到了几个问题,下面先来看作业. 一. 作业1: ...
- Python中变量的作用域(variable scope)
http://www.crifan.com/summary_python_variable_effective_scope/ 解释python中变量的作用域 示例: 1.代码版 #!/usr/bin/ ...
- python学习笔记11(函数二): 参数的传递、变量的作用域
一.函数形参和实参的区别 形参全称是形式参数,在用def关键字定义函数时函数名后面括号里的变量称作为形式参数. 实参全称为实际参数,在调用函数时提供的值或者变量称作为实际参数. >>> ...
随机推荐
- 用磁盘工具刻录MACOSX系统启动盘方法
些系统盘用Toast 刻录后无法引导,建议使用磁盘工具刻录系统盘 老手可能早知道这了,仅供新手参考 在应用程序-->实用工具里找到磁盘工具,打开. 将DMG文件拖放到磁盘工具窗口,双击DMG文件 ...
- ajax async异步
async默认的设置值为true,这种情况为异步方式,就是说当ajax发送请求后,在等待server端返回的这个过程中,前台会继续执行ajax块后面的脚本,直到server端返回正确的结果才会去执行s ...
- Python时间操作所相关
相关模块:time,datetime,calendar(日历模块) 获取当前时间: # 获取当前10位时间戳,默认返回为float类型 print int(time.time()) # output: ...
- Spring5源码分析(1)设计思想与结构
1 源码地址(带有中文注解)git@github.com:yakax/spring-framework-5.0.2.RELEASE--.git Spring 的设计初衷其实就是为了简化我们的开发 基于 ...
- hexo-next-travis-ci 构建自动化部署博客
构建效果如上面视频所示,如果浏览器不支持请戳一下链接: 自动化部署构建效果 .只要将编辑的 .md 文件推送到 github 上,博客网站就可以更新这篇文章. 其实差不多半年前也构建过一次,由于安装 ...
- 在CodaLab上提交MURA竞赛的结果
What is MURA? MURA (musculoskeletal radiographs) is a large dataset of bone X-rays. Algorithms are t ...
- 7/8段码管(LED)
LED显示器在许多的数字系统中作为显示输出设备,使用非常广泛.它的结构是由发光二极管构成的a.b.c.d.e.f和g七段,并由此得名,实际上每个LED还有一个发光段dp,一般用于表示小数点,所以也有少 ...
- Linux USB 鼠标驱动程序详解(转)
Linux USB 鼠标驱动程序详解 USB 总线引出两个重要的链表!一个 USB 总线引出两个重要的链表,一个为 USB 设备链表,一个为 USB 驱动链表.设备链表包含各种系统中的 USB 设备以 ...
- Mysql(或者sqlite), Mongo中update Column + 1
Mysql(或者sqlite), Mongo中update Column + 1 有类似以下需求,在数据库表里有一个字段,记录了一个count,然后又时候需要在count的基础上加上某个数字,比如1. ...
- Django中使用websocket并实现简易聊天室
django使用websocket并实现简易聊天室 django默认只支持http协议 如果你想让django即支持http协议又支持websocket协议,则需要做以下配置 前期配置 前提需要安装c ...