python function 2_ closures and decorators

Range of variables (local / global)

  • Local variables
    • In the variable declared inside a function
    • Unable to get outside the body of the function
  • Global Variables
    • Variables declared outside the function
    • All functions are accessible

In the function, the same name as the local and global variables, local variables precedence

name = '月月'
def fun2():
    name = '小月月'
    name += '会弹吉他'
    print(name)

fun2()
小月月会弹吉他

When you change the global variables in the function body, will attempt error

name = '月月'
def fun2():
    print(name)
    name += '会弹吉他'

fun2()

When the need to modify global variables in the function body, and needs global

Just get do not need to add

name = '月月'
def fun2():
    global name
    name += '会弹吉他'
    print(name)
fun2()
print(name)
月月会弹吉他
月月会弹吉他

When the function to modify the global variable is a variable type, such as a list, it is not necessary to add global keyword

list1 = ['python','php','go']
def fun2():
    list1.append('java')
fun2()
print(list1)
['python', 'php', 'go', 'java']

Internal function

Variables can access external functions

a = 10
def func1():
    b = 20
    def func2():
        print(a,b)
    func2()
func1()
10 20

Internal function can modify the function of external variables such as the type of the variable: list

list1 = ['python','php','go']
def func1():
    list2 = ['html','css']
    def func2():
        list1.append('java')
        list2.append('javascript')
        print(list1,list2,sep='\n')
    func2()
func1()
['python', 'php', 'go', 'java']
['html', 'css', 'javascript']

When the internal function modify global immutable variable, the variable name within the required function declaration global

a = 10
def func1():
    b = 20
    def func2():
        global a
        a += b
        print(a,b)
    func2()
func1()

Function modifies the internal variable immutable external functions, need to be declared in the internal function, the variable name nonlocal

a = 10
def func1():
    b = 20
    def func2():
        nonlocal b
        b += a
        print(a,b)
    func2()
func1()

4.1, locals (), you can see the current function variables declared in which the output in the form of a dictionary

a = 10
def func1():
    b = 20
    def func2():
        nonlocal b
        b += a
        print(locals())
    func2()
    print(locals())
func1()
{'b': 30}
{'func2': <function func1.<locals>.func2 at 0x000001BF232F4730>, 'b': 30}

globals (), there are those who view the global variables, output in the form of a dictionary (there will be some system of key-value pairs)

a = 10
def func1():
    b = 20
    def func2():
        nonlocal b
        b += a
        print(globals())
    func2()
func1()

Guess you like

Origin www.cnblogs.com/inmeditation/p/12337883.html