python--内部函数(十四)

python--内部函数(十四)

# 内嵌函数和闭包

# 将局部变量改为全局变量
count = 5   #定义全局变量count
def myfun():
    count = 10  #定义局部变量count
    print(count)
myfun() #调用myfun方法,打印的结果是count=10  说明当全局变量和局部变量重名时,先在局部查找这个指定的变量,如果没有在去全局查找。

# global 全局关键字
count = 5   #定义全局变量count
def myfun():
    global count    #用global修饰局部变量count,使其变为全局变量
    print(count)
myfun() #调用myfun方法,打印的结果是5,说明global count修饰局部变量变为全局变量成功。

# 内嵌函数==内部函数
def fun1():     #定义外层的方法
    print('fun1()方法正在被调用')
    def fun2():     #定义内部方法
        print('fun2()方法正在被调用。。。')
    fun2()  #在外层方法中调用内部方法

fun1()  #调用fun1()方法同时由fun1()调用fun2()方法   调用fun1()方法结果:fun1()方法正在被调用  fun2()方法正在被调用。。。

'''
闭包 函数式编程lisp
什么是闭包:1、存在内嵌关系,及外部函数内嵌了一个函数。2、外部函数定义的变量被内部函数引用。满足这两个条件就是是内部函数是外部函数的闭包

'''
def fun1(x):     #定义外层的方法
    print('fun1()方法正在被调用')
    def fun2(y):     #定义内部方法,调用外部函数的变量
        print('fun2()方法正在被调用。。。')
        return  x * y
    return fun2 #返回fun2的值
i = fun1(5)(7)  #调用fun1同时给fun1和fun2传递参数
print(i)    #打印fun1和fun2的值

# 闭包中如果在内部函数中修改外部函数变量,会引发错误。
# 原因是内部方法的局部变量名称和外部方法的变量名称一样,且作用域范围不一样导致的。
# 解决的方法就是在内部方法中将这个重名的变量申明为nonlocal
def fun1():
    x = 5
    def fun2():
        nonlocal x  #将x变量设置为nonlocal
        x +=x
        return x
    return fun2()
i = fun1()
print(i)    #结果为10


猜你喜欢

转载自blog.csdn.net/m0_38039437/article/details/80336010