function scopes in Python
In Python, a function is a scope
=‘xiaoyafei‘def change_name(): =‘肖亚飞‘ print(‘在change_name里的name:‘,name)change_name() # 调用函数print("在外面的name:",name)
The results of the operation are as follows:
在change_name里的name: 肖亚飞在外面的name: xiaoyafei
Let's try again how is it found in nested functions?
=15def func(): print(‘第一层age:‘,age) # 第一层age: 15 def func2(): =73 print("func2中的age:",age) # func2中的age: 73 def func3(): =84 print("func3中的age:",age) # func3中的age: 84 func3() # 调用func3函数 func2() # 调用func2函数func()
In the above nested function, it is well explained that a function is a scope, then we can now change the code a little bit to see the situation?
=15def func(): print(‘第一层age:‘,age) # 第一层age: 15 def func2(): print("func2中的age:",age) # func2中的age: 15 # 看到没有,如果当前作用域里没有age变量,那么它就会往上找 def func3(): =84 print("func3中的age:",age) # func3中的age: 84 func3() # 调用func3函数 func2() # 调用func2函数func()
Well, then, when someone says, "a whole bunch of crap is about local variables and global variables, then I want to ask: in this nested function, there is no age variable in Func2, so how does it find the global variable, age = 15?"
Now we need to look at the scope lookup order:
Variable Scope LEGB
- namespaces within the L:locals function, including local variables and arguments
- E:enclosing the namespace of the outer nested function, that is, adjacent to the previous layer, for example, said: FUNC2 No age variable will go to the Func find this
- G:globals Global Variables
- B:builtins the namespace of the built-in module
Cough, or first understand what is the name space?
namespace, aka name space , as the name implies is the place to store names, what name? for example, x = 1, 1 is stored in memory, so where is the variable name x stored? Namespaces are places where names X and 1 bind.
>>>=1>>>id(1)1576430608
The namespace is divided into the following 3 types:
- Locals: is a namespace within a function, including local variables and formal parameters
- GLOBALS: global variable, the namespace of the module in which the function is defined
- Builtins: Namespaces for built-in modules
Different scopes of variables are determined by the namespace in which the variable resides.
Scope is range
- Global scope: Global survival, globally valid
- Local scope: Temporary inventory, partially valid
Let's take an example to see
Level= ' L0 'N= AdefFunc (): Level= ' L1 'N= - Print(Locals())# {' n ':, ' Level ': ' L1 '} defOuter (): N= -Level= ' L2 ' Print(Locals(), N)# {' Level ': ' L2 ', ' n ': +} defInner (): level= ' L3 ' Print(Locals(), N)# {' Level ': ' L3 ', ' n ': +}Inner () outer () func ()
With the rules of L-E-G-->b, that is: in the local can not find, will go to local outside the local search (such as closures), and can not find the global find, and then go to the built-in function to find.
Python function scope