zoukankan      html  css  js  c++  java
  • 内嵌函数和闭包

    #内嵌函数和闭包
    '''
    全局变量与函数中的变量
    global:改变全局变量
    '''
    count=5#全局变量
    def my():
        count=10#局部变量
        print(count)
    my()#10
    def my():
        global count
        count=10
        print(count)
    my()#10
    '''
    内嵌函数
    '''
    def fun1():
        print("fun1在被调用")
        def fun2():
            print("fun2在被调用")
        fun2()
    fun1()#fun1在被调用fun2在被调用
    '''
    闭包(clocune)对代码进行提炼与概括,公共用式
    '''
    def funx(x):
        def funy(y):
            return x*y
        return funy
    print(funx(3)(5))#15
    '''
    def funx(x):
        def funy(y):
            return x*y
        return funy
    像return funy中调用不是funy()在这个函数中,funy是一个处于funx中的局部变量函数,在funy()没有被定义前调用funy是会出现x与
    y未进行赋值的情况。
    在整个函数流程中,funy是funx的局部变量,funy返回的是x*y,而funx返回的是funy运行调用的结果,由于这是一个有参数的函数,
    所以在调用函数前都需要将方法进行参数的赋值。
    '''
    def fun1():
        x=[5]
        def fun2():
             x[0] *= x[0]
             return x[0]
        return fun2()
    print(fun1())#25
    '''
    def fun1():
        x=5
        def fun2():
            x *= x
            return x
        return fun2()
    fun2是fun1中的局部变量,x=5是fun2的全局变量,fun2中的x未进行定义,所以不能访问到x=5的全局变量
    更改将x放到列表中
    '''
    '''
    nonlocal申明不是局部变量
    '''
    def fun1():
        x=5
        def fun2():
            nonlocal x
            x *= x
            return x
        return fun2()
    print(fun1())#25
  • 相关阅读:
    在web应用中使用MEF插件式开发
    IBatis更名为mybatis
    ssh公钥登录
    android摄像头获取图像——第二弹
    android摄像头获取图像——第一弹
    堆排序
    配置开发环境及相关问题
    android摄像头获取图像——第三弹
    冒泡排序
    Linux中环境变量文件及配置
  • 原文地址:https://www.cnblogs.com/H-Yan/p/14173434.html
Copyright © 2011-2022 走看看