Advanced Python Scope 02

First, the scope

Scope for variable, means may declare the scope of application of the variable in the program.

Is a function, class, module generates a scope, the scope will not block. For example loops, if determined not to generate scope.

 

Second, the scope chain

Python in the scope chain, variable would go from the inside out, go find their own scope, I did not go in to a higher level, until not found error.

Characteristics: before the function is not performed, the scope has been formed, the scope chain also generated.

name = "lzl"
 
def f1():
    print(name)
 
def f2():
    name = "eric"
    f1()
f2()
结果:
lzl

Here are explained:

F1 and f2 is performed in, f1 scope chain has been formed, to find higher, name of lzl.

 

Third, global and local variables

Global Variables: All variables outside the function definition.

Local variables: internal variables defined function or class variable in a module.

 

If the variable name inside the function the first time, and appears in front of =, is considered a local variable is defined, there is no global domain regardless of the variable name, the function will be used in local variables.

(Ie, declare a new local variable. If this variable name and the names of all the variables the same, then the local variable names will override the global variable name.)

a = 10
b = 20
 
def fun():
 
    a = 1
    b = 10
    print('locals: ', locals())

fun()
print('globals: ', globals())

结果:
locals:  {'a': 1, 'b': 10}
globals:  {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a2f0080>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Volumes/DATA/python/python_test/test.py', '__cached__': None, 'a': 10, 'b': 20, 'fun': <function fun at 0x10a283268>}

 

Fourth, the use of global variables in the function ( be sure to caution global variable )

If you just read the global variables will not have any problems.

If you want to re-associate a global variable, you need to use the keyword global.

= 100 _num DEF FUNC ():
     , Ltd. Free Join _num   # declare the Num is global. If you already have this global variable Num variable that refers to the global if it is not the Num it a new definition of global variables. 
    = 200 _num Print (_num) 
FUNC () Print (_num)   # output 200 illustrates the global variable is modified


    

 

Reference article:

https://www.cnblogs.com/goldsunshine/p/10948475.html

 

Guess you like

Origin www.cnblogs.com/mazhiyong/p/12516323.html