内嵌函数

print("================内嵌函数=====================")
def fun1():
    print("I am the fun1()")
    def fun2():
        print("I am the fun2()")
fun1()
fun2()

函数内调函数

print("================内嵌函数=====================")
def fun1():
    print("I am the fun1()")
    def fun2():
        print("I am the fun2()")
    fun2()
fun1()
fun2()

闭包

print("================闭包====================")
def funX(x):
    def funY(y):
        return x*y
    return funY
i=funX(8)
print(i)
print("type:i="+str(type(i)))
print("i(5)="+str(i(5)))

x作用域问题

x是外部变量,不能被fun2直接使用。

def fun1():
    x=5
    def fun2():
        x*=x
        return x
    return fun2()
fun1()

利用列表改变原x作用域

def fun1():
    x=[5]
    def fun2():
        x[0]*=x[0]
        return x[0]
    return fun2()
temp=fun1()
print("temp="+str(temp))

关键字nonlacal解决x作用域

def fun1():
    x=5
    def fun2():
        nonlocal x
        x*=x
        return x
    return fun2()
fun1()
发布了182 篇原创文章 · 获赞 81 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_41498261/article/details/104546073