zoukankan      html  css  js  c++  java
  • python闭包

    创建闭包:

    1、闭包函数必须有内嵌函数;

    2、内嵌内部的函数必须引用上一级函数的变量;

    3、闭包函数必须返回内嵌函数

    def closure_func():
    in_func="in test"
    def f():
    return in_func
    return f

    ff=closure_func() #此时的ff=f
    print(ff())#ff()=f(),函数f()访问了外部函数的局部变量

    ff就是一个闭包,包括了f()函数和自由变量in_func

    def make_power(x):
    def f(y):
    return y,x
    return f
    power_two=make_power(2)
    print(power_two(5))
    print(power_two.__closure__[0].cell_contents)#自由参数

    (5, 2)
    2

    闭包容易出现的错误:

    1、外部函数局部变量;

    def out_test():
        out_def='Out test'
        def inner_test():
            nonlocal out_def
            out_def='test'
            return out_def
        print('before:{}'.format(out_def))
        inner_test()
        print('after:{}'.format(out_def))
    
    out_test()
    运行结果:

    before:Out test
    after:test

    def out_test():
    out_def='Out test'
    def inner_test():
    nonlocal out_def
    out_def='test'
    return out_def
    print('before:{}'.format(out_def))
    inner_test()
    print('after:{}'.format(out_def))

    out_test()

    运行结果:

    before:Out test
    after:test

     

    2、循环问题,返回函数不要引用任何循环变量,或者后续会发生变化的变量

    def count():
        fs=[]
        for i in range(1,4):
            def f():
                return i*i
            fs.append(f)
            print(fs)
        return fs
    
    f1,f2,f3=count()
    print(f1(),f2(),f3())
    
    运行结果:
    9 9 9
    
    可debug查看代码运行情况:返回的函数并没有立即执行,而是直到调用了f()才执行,在上面的例子中,每次循环都创建了一个新的函数,然后,把创建的3个函数都返回了
    修改上面的函数:
    def count():
        def f(j):
            return lambda:j*j;
        fs=[]
        for i in range(1,4):
            fs.append(f(i))
        return fs
    
    f1,f2,f3=count()
    print(f1(),f2(),f3())
    运行结果:
    1、4、9
    

      

    转自: https://www.jianshu.com/p/2680ea4cc7b8?utm_campaign=hugo&utm_medium=reader_share&utm_content=note&utm_source=weixin-friends

  • 相关阅读:
    【转】【MFC】 StretchBlt绘图图像失真
    【转】MFC 各类型相互转换
    【转】MFC CListCtrl 使用技巧
    【数学】关于已知线段长度获取某一点对应线段的百分比
    【MySQL】MySQL 常用语法之锁表与解锁表
    C#通用类库
    WPF Knowledge Points
    WPF中的WndProc
    C# 重写WndProc 拦截 发送 系统消息 + windows消息常量值
    c#正则获取html里面a标签href的值
  • 原文地址:https://www.cnblogs.com/xianhaiyan/p/14396191.html
Copyright © 2011-2022 走看看