变量作用域

  • 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 - 变量的作用域的更多相关文章

  1. Python变量的作用域在编译过程中确定

    为了节省读友的时间,先上结论(对于过程和细节感兴趣的读友可以继续往下阅读,一探究竟): [结论] 1)Python并不是传统意义上的逐行解释型的脚本语言 2)Python变量的作用域在编译过程就已经确 ...

  2. Python——变量的作用域

    原创声明:本文系博主原创文章,转载及引用请注明出处. 1. 在编程语言中,变量都有一定的作用域,用来限定其生命周期,且不同类型的变量作用域不同. 在Python中解释器引用变量的顺序(优先级)为:当前 ...

  3. 『无为则无心』Python函数 — 30、Python变量的作用域

    目录 1.作用于的概念 2.局部变量 3.全局变量 4.变量的查找 5.作用域中可变数据类型变量 6.多函数程序执行流程 1.作用于的概念 变量作用域指的是变量生效的范围,在Python中一共有两种作 ...

  4. Python变量的作用域

    局部变量 局部变量是指在函数内部定义并使用的变量,他只在函数内部有效.即函数内部的名字只在函数运行时才会创建,在函数运行之前或者运行完毕之后,所有的名字就都不存在了.所以,如果在函数外部使用函数内部定 ...

  5. python中对变量的作用域LEGB、闭包、装饰器基本理解

    一.作用域 在Python程序中创建.改变.查找变量名时,都是在一个保存变量名的空间中进行,我们称之为命名空间,也被称之为作用域.python的作用域是静态的,在源代码中变量名被赋值的位置决定了该变量 ...

  6. Python学习之变量的作用域

    学习地址:http://www.jianshu.com/p/17a9d8584530 1.变量作用域LEGB 1.1变量的作用域 在Python程序中创建.改变.查找变量名时,都是在一个保存变量名的空 ...

  7. python命名空间、作用域、闭包与传值传引用

    (以下内容,均基于python3) 最近在看python函数部分,讲到了python的作用域问题,然后又讲了Python的闭包问题. 在做作业的时候,我遇到了几个问题,下面先来看作业. 一. 作业1: ...

  8. Python中变量的作用域(variable scope)

    http://www.crifan.com/summary_python_variable_effective_scope/ 解释python中变量的作用域 示例: 1.代码版 #!/usr/bin/ ...

  9. python学习笔记11(函数二): 参数的传递、变量的作用域

    一.函数形参和实参的区别 形参全称是形式参数,在用def关键字定义函数时函数名后面括号里的变量称作为形式参数. 实参全称为实际参数,在调用函数时提供的值或者变量称作为实际参数. >>> ...

随机推荐

  1. bootstrap实现多选项及回显

    1.前端 <link rel="stylesheet" href="${ctxStatic}/js/bootstrap-select-1.12.2/dist/css ...

  2. LeetCode Day 3

    LeetCode0003 给定一个字符串,请你找出其中不含有重复字符的最长子串的长度. 示例 1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 & ...

  3. LG_3459_[POI2007]MEG-Megalopolis

    题目描述 Byteotia has been eventually touched by globalisation, and so has Byteasar the Postman, who onc ...

  4. Oauth2.0 协议简介及 php实例代码

    转自:http://www.dahouduan.com/2017/11/21/oauth2-php/ https://blog.csdn.net/halsonhe/article/details/81 ...

  5. 关于HTTP请求GET和POST的区别

    1.GET提交,请求的数据会附在URL之后(就是把数据放置在HTTP协议头<request-line>中),以?分割URL和传输数据,多个参数用&连接;例如:login.actio ...

  6. POJ 2553 The Bottom of a Graph Tarjan找环缩点(题解解释输入)

    Description We will use the following (standard) definitions from graph theory. Let V be a nonempty ...

  7. js 实现排序算法 -- 希尔排序(Shell Sort)

    原文: 十大经典排序算法(动图演示) 希尔排序 1959年Shell发明,第一个突破O(n2)的排序算法,是简单插入排序的改进版.它与插入排序的不同之处在于,它会优先比较距离较远的元素.希尔排序又叫缩 ...

  8. [转]<版本二>写代码的小女孩

    天冷极了,下着雪,又快黑了.这是一年的最后一天——大年夜.在这又冷又黑的晚上,一个乖巧的小女孩在机房里调试程序.她从家里出来的时候还穿着一件外套,但是有什么用呢?那是一双很大的外套——那么大,不知是哪 ...

  9. MyBatis XML 配置文件 properties 元素扩展

    在分析 MyBatis XML 配置文件 properties 元素时提到了三种配置方式,其中 property 子元素 和 properties 文件都比较容易理解,但是为什么还要提供一种代码参数传 ...

  10. python IO多路复用版FTP

    需求: 实现文件上传及下载功能 支持多连接并发传文件 使用select or selectors