In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article "what is Python global space and local space", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what is Python global space and local space" article.
I. Space and local space 1. Namespace
The concept of namespaces is proposed to divide and control whether variables are visible and the length of the life cycle; the scope of namespaces is called scope.
Divide an area to store all data and store it in a dictionary (variables and values form a mapping relationship). There are three kinds.
Built-in namespaces:
The interpreter is created when it is started, and the life cycle is the longest until the interpreter has finished running.
Global Namespace:
The file is created at run time until the end of the interpreter, and the life cycle is longer.
Local namespace:
When the number is called, the local variables are created and released after the call, and the life cycle is shorter.
Create and destroy order
Creation order:
Python interpreter launch-> create a built-in namespace-> create a global namespace-> create a local namespace
Destroy order:
After the function call-> destroy the local namespace data corresponding to the function-> destroy the global namespace data-> destroy the built-in namespace data
2. Global and local variables
What are global and local variables:
The local variable is the variable defined inside the function, the local variable is in the local namespace, and the scope is only visible inside the function, that is to say, it can only be used inside the function.
# the variable created in the function is the local variable def func (): var = 'local variable' # A local variable cannot use print (var) # error in a non-corresponding local environment, the variable does not exist
Global variables are defined outside the function or inside the function using global. The namespace of the global variable is the global namespace and the scope spans the entire file, that is, global variables can be used anywhere in the whole file.
# the variable created in the global environment is the global variable var = 'global variable' def func (): # the global variable print (var) # global variable func () can also be used locally
It is best not to use local variables with the same name as global variables. If they have the same name, global variables cannot be used in the local environment.
Var = 'global variable' def func (): # first use the global variable print (var) # error, which cannot be found # and then the local variable and the global variable have the same name, then the new local variable will override all the influence of the global variable in the local space, which is called the local variable modifies the global variable # in this case, the global variable can no longer be used in the local space, and the variable previously used in the local space becomes called first and defined later; resulting in an error. Var = 'local variable' print (var) func () # but the local variable with the same name does not affect the value of the global variable print (var) # global variable
Built-in functions are built-in namespaces, which refer to those built-in functions that come with python.
3. Scope
Local variable scope: inside the function
Global variable scope: across the entire file
4. Life cycle
Built-in variables-> global variables-> local variables
Built-in variables are not released until the end of the python program, starting when the python program is running
Global variables are not released from creation until the program is finished or cleared.
The creation of the local variable word begins and will be released until the local space execution is finished or cleared.
5. The use of all local functions and keywords
Function
Globals ()
Returns the contents of all global scopes.
If, globally, after calling globals, you get all the variables before printing, return the dictionary, global space scope
# define some global variables a, b, c = 1,2, call the globals function res = globals () # print for the first time Contains a b cprint (res)''results: {' _ name__':'_ _ main__','_ _ doc__': None,'_ _ package__': None,'_ _ loader__':,'_ _ spec__': None,'_ _ annotations__': {},'_ _ builtins__':,'_ _ file__': 'ERAR' '_ _ cached__': None,' asides: 1, 'baked: 2,' cations: 3, 'res': {...}}''# and define some variables d, e, f = 1,2, printing for the second time Contains a b c de fprint (res)''results: {' _ name__':'_ _ main__','_ _ doc__': None,'_ _ package__': None,'_ _ loader__':,'_ _ spec__': None,'_ _ annotations__': {},'_ _ builtins__':,'_ _ file__': 'ERAR' '_ _ cached__': None,' asides: 1, 'breadth: 2,' cations: 3, 'res': {...},' dudes: 1, 'eBay: 2,' fags: 3}''
If, locally, after calling globals, you get the variables used before the call, return the dictionary, global space scope
# define some global variables a, b, c = 1,2, using the globals function def func (): res = globals () print (res) # call function func ()''result: does not contain def {' _ name__':'_ main__','_ doc__': None,'_ package__': None,'_ loader__': in the local environment '_ _ spec__': None,' _ _ annotations__': {},'_ _ builtins__':,'_ _ file__': 'EVRAPUG0ProjectAccording to Test6.pythons,' _ _ cached__': None, 'asides: 1,' baked: 2, 'cations: 3,' func':}''# define some global variables d, e, f = 4,5 The second call function func ()''result: contains de f {' _ name__':'_ main__','_ doc__': None,'_ _ package__': None,'_ _ loader__':,'_ _ spec__': None,'_ _ annotations__': {},'_ _ builtins__': '_ _ file__':' Elux cached__': None: 3, 'func':,' daddy: 4, 'eBay: 5,' fission: 6}'
Globals can create global variables dynamically
Dic = globals () print (dic) # returns the dictionary of the system''result: {' _ name__':'_ main__','_ doc__': None,'_ _ package__': None,'_ _ loader__':,'_ _ spec__': None,'_ _ annotations__': {},'_ _ builtins__': '_ _ file__':' eVERUGUR 0murpProjectAccording to the global dictionary,'_ _ cached__': None, 'dic': {.}}''# in the global dictionary By adding a key-value pair, a global variable is automatically created, and the corresponding key is the variable name The corresponding value is the value pointed to by the variable dic ['msr123123123'] =' 123456'print (msr123123123) # 12345 view global content print (dic) 'result: {' _ name__':'_ main__','_ doc__': None,'_ package__': None,'_ loader__':,'_ spec__': None,'_ annotations__': {},'_ builtins__': '_ _ file__':' eVERUGUP 0MuyProjectAccording to CeshiAccord test6.python,'_ _ cached__': None, 'dic': {...},' msr123123123': '123456'}'
Locals ()
Returns all contents of the current scope.
If in the global, after calling locals, get all the variables before printing, return the dictionary, global space scope
# define some global variables a, b, c = 1,2, call the locals function res = locals () # print for the first time Contains a b cprint (res)''results: {' _ name__':'_ _ main__','_ _ doc__': None,'_ _ package__': None,'_ _ loader__':,'_ _ spec__': None,'_ _ annotations__': {},'_ _ builtins__':,'_ _ file__': 'ERAR '_ _ cached__': None,' asides: 1, 'baked: 2,' cations: 3, 'res': {...}}''# and define some variables d, e, f = 1,2, printing for the second time Contains a b c de fprint (res)''results: {' _ name__':'_ _ main__','_ _ doc__': None,'_ _ package__': None,'_ _ loader__':,'_ _ spec__': None,'_ _ annotations__': {},'_ _ builtins__':,'_ _ file__': 'ERAR '_ _ cached__': None,' asides: 1, 'breadth: 2,' cations: 3, 'res': {...},' dudes: 1, 'eBay: 2,' fags: 3}''
If you are locally, after calling locals, you will get all the variables before the call, return the dictionary, and the local space scope
# define some local variables def func (): # Local variables aa, bb, cc = 11,22,33 # first call res = locals () # print for the first time, including aa bb cc print (res) # {'cc': 33,' bb': 22, 'aa': 11} # and define some local variables dd, ee, ff = 44, 55, 66 # print for the second time Does not include dd ee ff print (res) # {'cc': 33,' bb': 22, 'aa': 11} # call the second time res2 = locals () # print the first call Contains dd ee ff print (res) # {'cc': 33,' bb': 22, 'aa': 11,' ff': 66, 'ee': 55,' dd': 44, 'res': {...}} # print the second call Contains dd ee ff print (res2) # {'cc': 33,' bb': 22, 'aa': 11,' ff': 66, 'ee': 55,' dd': 44, 'res': {...}} # to call the function and return the local variable func () in the function
Keyword
Global
Variables created in the local environment are local variables and cannot be used in the global environment. But a variable defined using global is a global variable that can be used in a global environment.
Def func (): var = 'local variable' global glvar glvar = 'global variable' # be sure to execute the local environment func () # print (var) # error in the global environment, the local variable cannot be called # the variable defined by global is the global variable print (glvar) # global variable
The value of a global variable cannot be modified in a local environment, and global can be used to modify a global variable in a local environment.
Var = 'global variable' def func (): global var var = 'modify in local environment' func () print (var) # modify in local environment 6. Nesting of functions
Before learning nonlocal, we need to learn some knowledge about function nesting.
Inner function and outer function
Functions can be nested within each other. The outer layer is called the outer function and the inner layer is called the inner function.
Def outer (): print ('my name is outer, is an outer function') def inner (): print ('my name is inner, inside outer, it's an inner function') # execute inner function inner () # execute outer function outer () 'result: my name is outer, it's an external function, my name is inner, inside outer, it's an inner function.
An inner function cannot be called directly outside a function.
After the outer function is called, the inner function cannot be called outside the function.
Internal functions can only be called internally by external functions.
When the inner function is called inside the outer function, there is a sequence, which must be defined in the call first, because python does not have a pre-reading mechanism, which is applicable to all scenarios in python.
# the outer layer is outer, the inner layer is inner, and the innermost layer is smaller. Call all the codes in smaller def outer (): print ('my name is outer, which is the outermost function and is the outer function of inner and smaller') def inner (): print ('my name is inner, the inner function of outer and the outer function of smaller') def smaller (): print ('my name is smaller Is the inner function of outer and inner () # first execute smaller smaller () # and then execute inner inner () # and then execute outer in outer before executing the smaller function outer () 'result: my name is outer, the outermost function, the external function of inner and smaller, my name is inner, the inner function of outer, the external function of smaller, my name is smaller, the inner function of outer and inner
When we nest multiple functions, we should note that no matter the outer function or the inner function, it is a function, as long as the variables in the function are local variables.
The connotation can use the local variable of the outer function, and the outer function cannot directly use the local variable of the inner function.
II. LEGB principle
LEGB principle is a principle of finding variables nearby, according to the principle of proximity, from the bottom to the top, from the inside to the outside, in turn.
B----Builtin (Python): the namespace of the Python built-in module (built-in scope)
G----Global (module): the namespace outside the function (global scope)
E----Enclosing Function Locals: scope of externally nested functions (nested scope)
L----Local (Function): scope within the current function (local scope)
Nonlocal
Now let's formally learn the nonlocal keyword, and the role of nonlocal is to modify the local variables at the upper level of the current local environment. Then according to this role, we know that the environment in which nonlocal is used is at least a secondary nested environment, and there must be a local variable in the outer local environment.
Def outer (): # define variable lvar = 'outer var' def inner (): # functions use nonlocal to modify the local variable nonlocal lvar lvar =' inner var' # to execute the inner function inner () print (lvar) outer () # inner var
What if there is no such variable in the local environment above, then look up according to the LEGB principle.
Def outer (): # defines the variable lvar = 'outer var' def inner (): def smaller (): # smaller modifies the variable, but not in inner Look up and modify the variable nonlocal lvar lvar = 'smaller var' # execute the smaller function smaller () # execute the inner function inner () print (lvar) # execute the outer function outer ()
If you search until there is no such variable in the outermost function, an error will be reported, because nonlocal will only modify the local variable, and if it goes out of range, it will report an error.
Var = 1 # variable is outside the outermost function, that is, global variable. Nonlocal cannot modify def outer (): def inner (): def smaller (): nonlocal var # error, no local variable var = 2 print (var) smaller () inner () outer () III.
Global and local variables
A global variable can be called in a local environment, but cannot be modified (but the value can be modified if the global variable is variable data)
Local variables cannot be called or modified in the global environment
Function
Global ()
(used inside a function to manipulate global variables)
1. Global variables can be defined in the local environment
2. Global variables can be modified in the local environment
Nonlocal ()
(used in the inner function, you can modify the local variables in the outer function)
Keywords:
Locals
1. Locals gets all the variables in the current scope
If you get all the variables before printing after the global call to locals, return the dictionary, global scope
If you get all the variables before the call after the local call to loclas, return the dictionary, local scope
Globals
2. Globals only gets all the variables in the global space
If you get the variables used before printing after the global call to globals, return the dictionary, global scope
If you get the variables used before the call after the local call to globals, return the dictionary, global scope
The above is the content of this article on "what is the global space and local space of Python". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.