全局变量和局部变量

#全局变量;顶头写的就是全局变量,就是没有缩进的变量;在任何位置都能调用
#局部变量;在子程序中定义的变量


name = "test"            #全局变量

def func():                #这个函数里面就是局部作用域
    global name            #定义位全局变量;上面的test就会被修改
    name = "多对多"        #局部变量
    print(name)
func()
print(name)


# 如果函数中无global的时候;优先读取局部变量;如果无局部变量,就读取全部变量;但是无法对全局变量重新赋值;但是对于可变类型;可以对它进行内部操作

s = ["a","b"]
def func1():
    s.append('c')       #对于可变类型;可以对它进行内部操作
    print(s)            #['a', 'b', 'c']
func1()
print(s)                #['a', 'b', 'c']


def test1():
    name = "test1"
    print(name)         #test1
    def test2():
        name = "test2"
        print(name)     #test2
        def test3():
            name = "test3"
            print(name) #test3
        print(name)     #test2
        test3()
    test2()
test1()


#nonlocal 是改变上一层的值
def js():
    val = "aaa"     #修改成了bbb
    def jp():
        nonlocal val #修改上层val为下面这个bbb的值
        val = "bbb"
        print(val)   #bbb
    jp()
    print(val)       #bbb
js()

def js():
    val = "aaa"
    def jp():
        val = "bbb"
        print(val)
        return jp
    return jp
js()()

猜你喜欢

转载自www.cnblogs.com/ajaxa/p/8966867.html