标签:python 变量 作用域 global nonlocal
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。if True:
x = 1;
print(x)
# 1这个是没有问题的,if并没有引入一个新的作用域,x仍处在当前作用域中,后面代码可以使用。def test():
x2 = 2
print(x2)
# NameError: name ‘x2‘ is not defineddef、class、lambda是可以引入新作用域的。count = 10
def outer():
print(count)
count = 100
print(count)
outer()
#UnboundLocalError: local variable ‘count‘ referenced before assignmentcount = 10
def outer():
count = 100
print(count)
outer()
#100内部作用域中直接声明了count=100,后面使用count都是内部作用域的了。count = 10
def outer():
global count
print(count)
count = 100
print(count)
outer()
#10
#100def outer():
count = 10
def inner():
nonlocal count
count = 20
print(count)
inner()
print(count)
outer()
#20
#20标签:python 变量 作用域 global nonlocal
原文地址:http://blog.csdn.net/xuepiaohan2006/article/details/25657399