变量作用域

  • 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. 关于Synchornized,Lock,AtomicBoolean和volatile的区别介绍

    1.  volatile 变量可以被看作是一种 "程度较轻的 synchronized". 2.  Lock 实现提供了比使用 synchronized 方法和语句可获得的更广泛的 ...

  2. Allure介绍

    以下内容基于pytest的框架进行展示: 什么是Allure Allure是一个独立的报告插件,生成美观易读的报告,目前支持语言:Java, PHP, Ruby, Python, Scala, C#. ...

  3. 关于log4j中log4j.properties和log4j.xml的加载顺序

    如果采用log4j输出日志,要对log4j加载配置文件的过程有所了解. log4j启动时,默认会寻找source folder下的log4j.xml配置文件,若没有,会寻找log4j.properti ...

  4. <SDOI2009>学校食堂

    我. 调了快一天 因为一个位置错误的感叹号 :-) !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 狗dp #include<cstdio> #include<cstr ...

  5. c++入门资源

    http://www.cnblogs.com/jackyyang7/articles/2479482.htmlvs2010编译器的使用 https://www.cnblogs.com/me115/ar ...

  6. 用shell脚本新建文件并自动生成头说明信息

    目标: 新建文件后,直接给文件写入下图信息 代码实现: [root@localhost test]# vi AutoHead.sh #!/bin/bash #此程序的功能是新建shell文件并自动生成 ...

  7. Numpy入门(二):Numpy数组索引切片和运算

    在Numpy中建立了数组或者矩阵后,需要访问数组里的成员,改变元素,并对数组进行切分和计算. 索引和切片 Numpy数组的访问模式和python中的list相似,在多维的数组中使用, 进行区分: 在p ...

  8. Git学习小结 ~ Lethe's Blog

    学习自https://www.liaoxuefeng.com/wiki/896043488029600 一.创建版本库 (1) git init 初始化一个Git仓库 (2)添加文件到Git仓库,分两 ...

  9. The Basic Of K8s

    k8s 基础概念 1.一个k8s集群包括 一个Master节点(主节点) 一群Node节点(计算节点) 2.Master节点 包括API Server.Scheduler.Controller man ...

  10. 常用JS代码片段

    1.隐藏部分数字,如手机号码,身份证号码 1 2 3 function (str,start,length,mask_char){ return str.replace(str.substr(star ...