The name of a function space
- Built-in space: storage space python interpreter built-in functions
- Global space: open runtime py file is stored in the relationship with all variables and values py file (inside out function) is executed after the end of the entire py file will disappear.
- Local space: a function definition, it will record the correspondence between the function name and the function body (nothing, as long as the memory address will only execute in memory temporarily opened a temporary space, storage function of the variables and values correspondence, disappear with the end of the function)
Loading order: inner space> Global Space> local space
Value order: local spaces> Global Space> inner space
Scope
Global scope: the built-in global space + space
The local scope: local space
Two nested functions
As long encounters a variable name () function is invoked, there is no () function call is not
After the implementation of a function call, the function body open space is automatically destroyed
2.1 Nesting
def func():
a = 1
def foo():
b = 2
print(b) # 2
print(a) # 1
def f1():
print(b) # 2
return f1()
return foo()
print(func())
result:
2
1
2
None
Local variables in space on a space nearby and use the global variable space, two local variables tied for space can not be used interchangeably
2.2 function reference each other
def a():
a = 1
c()
print(c)
def c():
c = 3
print(a)
def run():
a()
run()
result:
<function a at 0x0000000002101E18>
<function c at 0x00000000025B98C8>
The output is a function of the definition of a \ c of the memory address space of the built-in parallel variables can not be used interchangeably
2.3 global and nonlocal
1. global only modify the global variable corresponding to
a = 10
def func():
global a # 声明修改全局变量的值
a += 1
print(a)
func()
print(a)
result:
11
11
Modify global variables inside the function, if it does not exist in the global variable to create a
lst = ["麻花藤", "刘嘉玲", "詹姆斯"]
def func():
lst.append("马云") # 对于可变数据类型可以直接进行访问
print(lst)
func()
print(lst)
result:
[ 'Twist vine', 'Carina', 'James', 'Ma']
[ 'twist vine', 'Carina', 'James', 'Ma']
2. nonlocal modify variable values nearest local space, it does not modify the value of the global variable space
a = 10
def func():
def f1():
a = 20
def foo():
nonlocal a
a += 1
print(a) # 21
foo()
print(a) # 21
f1()
func()
print(a) # 10
Output:
21
21
10
Use three function name
The memory address of the function name
print(func)
Function name can be assigned to other variables
Function name can be passed as a parameter to the function
Note the point: when the transfer function names if + () is passed in the function's return value
Function name can be used as the function's return value is returned
Function name can be used as an element stored in a container