python class finishing 10 --- local variables and global variables

First, local variables and global variables

1. There is no indentation, the head write variables as global variables

2. In the variables defined in the subroutine as a local variable

3. Privatization of variables can only function

name = 'lhf' # globals
def change_name():
    name = 'Marshal than' # Local variables take effect only function in this section
    print (name) # start with the current scope to find the name, can not find the outer layer and then further to find

change_name()
print(name)

Second, modify global variables

1. global outermost always make use of global variables

NAME = 'lhf'
def change_name():
    global NAME # declare global variables, the outermost make use of global variables NAME
    NAME = "dabai" # modify global variables
    print(NAME)
print(NAME)
change_name()
print(NAME)

2. If there is no global keyword before the function of the internal variables, local variables priority to read, then read no local variables global variables

For variable variables can be operated inside the element, but can not re-assigned name = 'fff' variable itself

- have declared local variables

NAME = [1, 2]
def test():
    NAME = 'own' # and a new definition of a local variable
    print ( 'I love', NAME)
test()
print(NAME)

- no declaration of local variables

NAME = [1, 2]
def test():
    NAME.append ( 'you') # variable global variable internal modification
    print ( 'I love', NAME [2])
test()
print(NAME)

- There are global and local variables declared

NAME = [1, 2]
def test():
    global NAME
    NAME = 'own'
    print ( 'I love', NAME)
test()
print(NAME)

Examples of errors: both local variables within a function, there are global variables, the name is repeated, so the call fails

NAME = [1, 2]
def test():
    NAME = 'own'
    global NAME
    print ( 'I love', NAME)
test()
print(NAME)

Variables so we put the variable name of a global variable name in uppercase local variables in lower case

Third, there is the function of the program execution sequence

python code execution from the top down, but encountered the function is not executed, but only compiled when the call back function to perform.

name = 'white'

def cuoai():
    name = 'liu'
    DEF pianai ():
        global name
        name = 'wen'
    pianai ()
    print(name)
print(name)
cuoai ()
print(name)

Four, nonlocal refer to the primary variable, like global usage

name = 'white'

def cuoai():
    name = 'liu'
    DEF pianai ():
        nonlocal name
        name = 'wen'
    pianai ()
    print(name)
print(name)
cuoai ()
print(name)

Guess you like

Origin www.cnblogs.com/dabai123/p/11031342.html