Nested functions and the global and nonlacal

I. nested functions

  1. As long as met () function is invoked. If not () function call is not
  2. Execution order function
def fun1():   
    print(111)  
def fun2():   
    print(222)   
    fun1()   
fun2()
print(111)

1548388589142

def fun2():   
    print(222)   
    def fun3():       
        print(666)   
    print(444)   
    fun3()   
    print(888)
print(33)
fun2()
print(555)

1548388743478

# 函数中套函数
def func():
    a = 1
    def foo():
        b = 2
        print(b)  # 2
        print(a)  # 1
        def f1():
            print(b) # 2
        return f1()
    return foo()
print(func())
------------------------------------
# 函数嵌套调用
def func():
    a = 1
    foo()
    print(a)

def foo():
    b = 2
    print(b)
func()
-------------------------------------
# 函数嵌套参数的传递
def func(a):
    foo(a) #10

def foo(e):
    b(e) # return 10

def b(c):
    print(c)
    return 10

print(func(5))
-------------------------------------
# 函数嵌套返回值的传递
def func(a):
    foo(a) #10
    return 10
def foo(e):
    b(e)  
    return 10
def b(c):
    print(c)
    return 10

print(func(5))

二 .gloabal、nonlocal

First we write this code, first declare a global variable, and then call the local variable, and change the value of this variable

a = 100
def func():   
    global a    # 加了个global表示不再局部创建这个变量了. 而是直接使用全局的a   
    a = 28   
print(a)
func()
print(a)

global representation. no longer use the content of the local scope. The switch to variable global scope

global aim

Modify global variables inside the function, if it does not exist in the global variable to create a

lst = ["麻花藤", "刘嘉玲", "詹姆斯"]
def func():   
    lst.append("⻢云")   
    # 对于可变数据类型可以直接进⾏访问
   print(lst)
func()
print(lst)

nonlocal purpose

nonlocal modifications only one variable, the variable if one does not find one up on it, only to find the function of the outermost layer, will not find the global modification

a = 10
def func1():   
    a = 20   
    def func2():
        nonlocal a       
        a = 30       
        print(a)  
    func2()   
    print(a)
func1()


结果:
加了nonlocal
30
30

不加nonlocal
30
20

Look, if nested many layers, what effect would be a:

a = 1
def fun_1():   
    a = 2   
    def fun_2():       
        nonlocal a       
        a = 3       
        def fun_3():           
            a = 4           
            print(a)       
        print(a)       
        fun_3()       
        print(a)   
    print(a)   
    fun_2()   
    print(a)
print(a)
fun_1()
print(a)

If such a program can be analyzed to understand. So scopes, global, nonlocal no problem

Guess you like

Origin www.cnblogs.com/luckinlee/p/11620104.html