变量作用域

  • 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. 吴裕雄--天生自然python学习笔记:Python MongoDB

    MongoDB 是目前最流行的 NoSQL 数据库之一,使用的数据类型 BSON(类似 JSON). PyMongo Python 要连接 MongoDB 需要 MongoDB 驱动,这里我们使用 P ...

  2. baidumap 百度地图,实现多点之间的带方向路线图。

    通过lastVisitAt判断时间先后. 通过三角函数验证角度 再由baidumap 会制线段 绘制三角箭头 比较难看…… 测试个人 因为框架引用baidu 有各种问题失败,为最快实现,以此页作一个独 ...

  3. node 环境下简单web服务器搭建代码

    零.前置 已经安装 node 环境. 一.代码片段 var http = require('http'); var path = require('path'); var fs = require(' ...

  4. npm镜像源

    1.国内用户,建议将npm的注册表源设置为国内的镜像,可以大幅提升安装速度,先查看本机地址 npm config get registry 2.国内优秀npm镜像推荐及使用 淘宝npm镜像 ·搜索地址 ...

  5. Css兼容性大全

    知识有所欠缺  疯狂脑补抄袭经验中... 兼容性处理要点1.DOCTYPE 影响 CSS 处理 2.FF: 设置 padding 后, div 会增加 height 和 width, 但 IE 不会, ...

  6. 谈谈Spring的IoC之注解扫描

    问题   IoC是Inversion of Control的缩写,翻译过来即"控制反转".IoC可以说是Spring的灵魂,想要读懂Spring,必先读懂IoC.不过有时候硬着头皮 ...

  7. 为什么就连iPhone、三星手机的电池都能出问题?

    近年来关于三星.苹果.华为等知名手机厂商电池爆炸的消息一直不断在媒体上报道.这在一定程度上引发了消费者的重度忧虑,也给这些知名手机厂商从一定程度上造成了信任危机.为何连这些知名品牌都无法避免手机电池的 ...

  8. u-boot的环境变量详解

    u-boot的环境变量      u-boot的环境变量是使用u-boot的关键,它可以由你自己定义的,但是其中有一些也是大家经常使用,约定熟成的,有一些是u-boot自己定义的,更改这些名字会出现错 ...

  9. SpringBoot(七)-SpringBoot JPA-Hibernate

    步骤 1.在pom.xml添加mysql,spring-data-jpa依赖2.在application.properties文件中配置mysql连接配置文件3.在application.proper ...

  10. JSON parse error: Cannot deserialize value of type `java.util.Date` from String

    DateTimePicker + @DateTimeFormat("yyyy-MM-dd HH:mm:ss")日期格式转换异常 最近在做的一个项目使用的日期格式是yyyy-MM-d ...