# 变量作用域
# LEGB:Local ,Enclosing ,Global, Builtin
# 本地作用域,封闭,全局,内置
x = 1 # 全局变量
def add():
x += 1 # 局部变量复制错误
print(x)
add()
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-2-2cea274dfe02> in <module>()
8 print(x)
9
---> 10 add()
<ipython-input-2-2cea274dfe02> in add()
5 x = 1 # 全局变量
6 def add():
----> 7 x += 1 # 局部变量复制错误
8 print(x)
9
UnboundLocalError: local variable ‘x‘ referenced before assignment
x = 10 # 全局变量
def add():
print(x) # 引用全局变量
add()
10
x = 10
def add():
y = x + 1 # 局部变量不可以覆盖全局变量
print(y)
add()
11
error_list = [1,2,3,4]
def big_list():
error_list.append(100) # 修改列表erro_list,而不是重新赋值。
print(error_list)
big_list()
[1, 2, 3, 4, 100]
error_list = [1,2,3,4]
def big_list():
error_list += [100] # 修改列表erro_list,而不是重新赋值。局部变量在赋值之前被引用了
print(error_list)
big_list()
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-36-5469dd690471> in <module>()
4 print(error_list)
5
----> 6 big_list()
<ipython-input-36-5469dd690471> in big_list()
1 error_list = [1,2,3,4]
2 def big_list():
----> 3 error_list += [100] # 修改列表erro_list,而不是重新赋值。局部变量在赋值之前被引用了
4 print(error_list)
5
UnboundLocalError: local variable ‘error_list‘ referenced before assignment
error_list = [1,2,3,4]
def big_list():
new_list = error_list # 局部作用域
new_list += [100] # 修改列表erro_list,而不是重新赋值。
print(new_list)
big_list()
[1, 2, 3, 4, 100]
error_list = [1,2,3,4,5]
error_list += [12]
error_list
[1, 2, 3, 4, 5, 12]
error_list = [1,2,3,4,5]
error_list.append(12)
error_list # 与上面的结果一致。效果一致
[1, 2, 3, 4, 5, 12]
def calc(x,y):
def add(x,y):
print(‘x+y‘,x+y)
def sub(x,y):
print(‘x-y‘,x - y)
def mul(x,y):
print(‘x*y‘,x * y)
sub(x,y)
add(x,y)
calc(2,3)
x-y -1
x+y 5
def calc(x,y):
def add(x,y):
print(‘x+y‘,x+y)
def sub(x,y):
print(‘x-y‘,x - y)
def mul(x,y):
print(‘x*y‘,x * y)
sub(x,y)
add(x,y)
return mul #返回的是函数本身<function __main__.calc.<locals>.mul(x, y)>,主函数中的本地函数
calc(3,4)
x-y -1
x+y 7
<function __main__.calc.<locals>.mul(x, y)>
cc = calc(2,5) # print不是返回值,而是打印值,return才是返回值的用法。返回的函数赋给了cc,此时的作用域就是封闭作用域
x-y -3
x+y 7
print(cc)
<function calc.<locals>.mul at 0x0000022E88250B70>
cc(3,6)
x*y 18
# 闭包
def hello():
s = ‘coop‘ #在第一层和第二层中间添加的变量,闭包变量,又自由变量
def say():
# s += "what are you doing?"
print(s)
return say
hello #第一层函数
<function __main__.hello()>
hello() #第二层函数
<function __main__.hello.<locals>.say()>
h = hello() #返回的是函数say()
h()
coop
def hello():
s = ‘coop‘ #在第一层和第二层中间添加的变量,闭包变量,又自由变量
def say():
nonlocal s # global不推荐使用
s += "what are you doing?"
print(s)
return say
h = hello()
h()
coopwhat are you doing?
原文:http://blog.51cto.com/13118411/2111076