Heim  >  Artikel  >  Backend-Entwicklung  >  Python中的变量和作用域详解

Python中的变量和作用域详解

WBOY
WBOYOriginal
2016-08-04 08:55:391594Durchsuche

作用域介绍

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中的变量和作用域详解,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn