返回 Python中...... 登陆

Python中的变量和作用域详解

巴扎黑 2017-01-16 17:40:42 521

作用域介绍

python中的作用域分4种情况: L:local,局部作用域,即函数中定义的变量;

E:enclosing,嵌套的父级函数的局部作用域,即包含此函数的上级函数的局部作用域,但不是全局的;

G:globa,全局变量,就是模块级别定义的变量; B:built-in,系统固定模块里面的变量,比如int, bytearray等。 搜索变量的优先级顺序依次是:作用域局部>外层作用域>当前模块中的全局>python内置作用域,也就是LEGB。

x = int(2.9) # int built-in
g_count = 0 # global
def outer():
o_count = 1 # enclosing
def inner():
i_count = 2 # local

当然,local和enclosing是相对的,enclosing变量相对上层来说也是local。

#定义变量a
>>> a = 0
>>> print a
0
#定义函数p()
>>> def p():
... print a
...
>>> p()
0
#定义函数p2()
>>> def p2():
... print a
... a = 3
... print a
...
>>> p2() # 运行出错,外部变量a先被引用,不能重新赋值
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<interactive input>", line 2, in p2
UnboundLocalError: local variable 'a' referenced before assignment
#定义函数p3()
>>> def p3():
... a = 3 # 不引用直接赋值
... print a
...
>>> p3()
3
>>> print a
0 # 外部变量a并未改变

更多关于Python中的变量和作用域详解请关注PHP中文网(m.sbmmt.com)其他文章!    


最新手记推荐

• 用composer安装thinkphp框架的步骤 • 省市区接口说明 • 用thinkphp,后台新增栏目 • 管理员添加编辑删除 • 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消 回复 发送
  • PHP中文网