Original link: https://chegva.com/5504.html
◎Knowledge points
-
variable scope
-
Built-in functions locals() and globals()
◎Script practice
▽ Variable scope
""" The scope of a variable refers to the scope in which the variable acts. The scope of a variable is determined by where the variable is defined. There are four types of variable scopes: 1. Local scope (Local) Each time a function is called, a local scope is created. The variables defined in the local scope (function) are called local variables. The scope of local variables is: from the definition variable to the end of the function After the function call ends, its corresponding local All variables in the scope will be destroyed 2. Nested scope (Enclosing) A nested scope is created every time the outer function in the nested function is called. When a variable is defined in the outer function, the scope of the variable is: from the definition variable to the end of the function. After the outer function is called, its corresponding scope is All variables in nested scopes are destroyed (except closures) 3. Global scope (Global) Every time a module is run, a global scope is created. Variables defined in the global scope (module) are called global variables. The scope of global variables is: from the place where the variable is defined to the end of the module. All variables of will be destroyed 4. Built-in scope (Built-in) Every time you start the python interpreter, the built-in module is automatically loaded, thereby creating a function (built-in function) in the built-in scope of the built-in module, which can be used directly in the program. After stopping the interpreter, all variables in the built-in scope will be destroyed" "" def do_sth(a): print(a) b = 3 print(b) do_sth(2) # print(a) # NameError: name 'a' is not defined # print(b) # NameError: name 'b' is not defined def outer(): m = 5 def inner(): print(m) inner() outer() #5 # print(m) # NameError: name 'm' is not defined # print(g) # NameError: name 'g' is not defined g = 18 """ When a variable is accessed in a scope, the scope and all subsequent scopes are searched in turn in the order of LEGB, Stop searching if found, throw NameError if not found. Therefore, if a variable with the same name is defined in a different scope, According to the search order of LEGB, variables in the previous scope will mask variables of the same name defined in the following scope. """ print(id(123)) id = "Global" def outside(): id = "Enclosing" def inside(): id = "Local" print(id) inside() outside() # Annotate the ids in the order of LEGB, and check the result i = 11 def fun1(): i = 22 print(i) fun1() # 22 print(i) #11 j = 0 def fun2(): # print(j) # UnboundLocalError: local variable 'j' referenced before assignment j = 5 fun2() """ By default, the object referenced by the global variable cannot be modified in the local scope or nested scope (if the referenced object is of mutable type, the contents of the object can be modified) """ def f1(): # Redefine a local variable g and mask the global variable g # g = 19 # Equivalent to: g = g + 1, redefines a local variable g, and shields the global variable g # When calculating g + 1 on the right side of the equal sign, the newly defined local variable has not been assigned, so the program reports an error # g += 1 # UnboundLocalError: local variable 'g' referenced before assignment pass g2 = [3] def f2(): # Redefine a local variable g and mask the global variable g # g2 = [1] # The object referenced by the global variable g2 is of variable type, and the content of the object can be modified g2[0] = 8 """ If you want to modify the object referenced by the global variable in the local scope or nested scope, you can use the keyword global to declare the variable in the local scope or nested scope, thus indicating that in the local scope or nested scope The domain will not redefine a new variable with the same name, Instead use a global variable of that name. """ def f3(): global g g = 19 print(g) f3() #19 """ Flow control statements and exception handling statements do not create corresponding scopes, so variables defined in flow control statements and exception handling statements are still available after the execution of the statement ends. """ if True: temp = 18 print(temp) #18 for item in [1, 2, 3]: print(item) print(item) #3 try: result = 5 except: pass print(result) #5
▽ Built-in functions locals() and globals()
""" Namespace refers to the mapping of all names and values in a scope, represented by a dictionary. The built-in function locals() returns the namespace of all its local scopes. The built-in function globals() can return the namespace of all its local scopes. """ def outer(a): b = 8 def inner(c): d = 3 print(locals()) # {'a': 5, 'b': 8, 'inner': <function outer.<locals>.inner at 0x1021194c0>} outer(5) g = 2 class MyClass(object): pass print(globals()) """ locals() does not return the actual namespace, but a copy of the return value, so, modify the value corresponding to a name through locals(), There is no effect on the actual namespace; however, a map of names and values can be added to the actual namespace via locals(). """ def f(): x = 8 print(locals()) # {'x': 8} locals()['x'] = 9 locals()['y'] = 10 print(locals()) # {'x': 8, 'y': 10} f() """ globals() returns the actual namespace, so any modification to globals() is actually a modification to the actual namespace. """ globals()['g'] = 6 globals()['gg'] = 66 print(globals()) """ A masked global variable in the global scope can be accessed via globals() in the local scope or nested scope. """ def do_sth(): g = 123 print(globals()['g']) do_sth() #6 """ For the built-in function vars(), check its help information to: vars([object]) -> dictionary Without arguments, equivalent to locals(), With an argument, equivalent to object.__dict__. """
◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_advanced/variable_scope.py
This article is reprinted from: https://chegva.com/5504.html
This site is for inclusion only, and the copyright belongs to the original author.