One. Namespaces
1 / namespace (namespace): a place to store the name, is the division of the stack area, the arrival of the namespace can be stored in the stack area of the same name, the exact name of the space is divided into three, each name space independent
Ⅰ built-in namespace (built_in)
store name: python interpreter built-in keywords such as the name of
survival period: python interpreter starts is generated, python interpreter close then destroyed
Ⅱ global name space
to store name: if not within a function definition is not built, and the rest are global names
survival period: python file execution is generated, after the file has finished running python destruction
Ⅲ local namespace
name within the function during the operation of the function body code when calling the function generated: Store names
survival period: the function is called to produce, after the destruction of the function call is completed, call the same function several times to produce a few local name space
2 / namespace load order
Built-in namespace "global name space" local name space
3 / namespace order of destruction
The local name space "global name space" built-in namespace
4 / namespace lookup priority: from the current position, layer by layer to find
Ⅰ If the current local namespace
INPUT = 456
DEF Fun ():
INPUT = 123
Print (INPUT)
Fun ()
Ⅱ If the current in the global namespace
INPUT = 456 DEF Fun ():
INPUT = 123
Fun () Print (INPUT)
'Nested relation "5 / namespace: function definition stage to prevail, regardless of the position of the call, the name space is a separate zone in the stack, nested herein may be understood as different namespace there are the same variable name
x = 10
def fun(x):
print(x)
def foo():
x = 20
fun(x)
foo()
= 111 X
DEF FUNC ():
Print (X) # to prevail function definition phase, definition phase has produced a local variable, but this is called local variables are previously defined.
= 222 X
FUNC ()
two. Scope
Ⅰ global scope: built-in namespace & global namespace
global survival 1
2 effective global, shared by all functions
Ⅱ the local scope: local namespace
a temporary survival
second partial effective: the function of the effective
三。global & nonlocal
1/global-----可以在局部中修改全局变量的值,前提是全局变量是不可变类型
Ⅰ 不可变类型
x=111
def func():
global x # 声明x这个名字是全局的名字,不要再造新的名字了
x=222
func()
print(x)
Ⅱ 可变类型---在局部修改全局变量不需要用global进行声明
l=[111,222] def func(): l.append(333) func() print(l)
2/nonlocal------修改函数外层函数包含的名字对应的值(不可变类型)
x=0
def f3():
x=9
def f1():
x=11
def f2():
nonlocal x
x=22
f2()
print('f1内的x:',x) # 22
f1()
print('f3',x) # 9
f3()
print(x) # 0