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

    闭包

    因为python中函数也可以当作对象,所以如果出现当我们返回一个函数,而该函数含有外部变量的时候就形成了闭包。
    闭包的特点:

    1. 是个嵌套函数
    2. 可以获得非局部的变量
    3. 将函数当作对象返回

    看一个例子会更易理解:

    def make_printer(msg):
    
        msg = "hi there"
    
        def printer():
            print(msg)
    
        return printer
    
    myprinter = make_printer("Hello there")
    myprinter()
    
    hi there
    

    可以看出,myprinter返回的是函数对象(闭包特点3,1),而myprinter()则获取了printer()域之外的变量值(闭包特点2)

    闭包和nonlocal

    下面两个例子则是获得了域之外的,关键字nonlocal的使用获得累加的效果。

    def make_counter():
    
        count = 0
        def inner():
            nonlocal count  # 去掉报错,count是不可变类型
            count += 1
            return count
    
        return inner
    
    counter = make_counter()
    c = counter()
    print(c)
    c = counter()
    print(c)
    
    1
    2
    

    上文使用nonlocal 是因为int类型是不可变类型,若不使用nonlocal则,无法对inner()中的count 进行更改值
    而对可变类型,则例子如下:

    def make_summer():
        data = []
        def summer(val):
            data.append(val)
            _sum = sum(data)
            return _sum
        return summer
    
    summer = make_summer()
    
    s = summer(1)
    print(s)
    s = summer(2)
    print(s)
    
    1
    3
    
  • 相关阅读:
    SQL语句的优化(转载)
    使用经纬度得到位置Geocorder
    android自带下拉刷新SwipeRefreshLayout
    线程池ScheduledThreadPool
    线程池SingleThreadPool
    线程池CachedThreadPool
    线程池FixedThreadPool
    线程池ThreadPoolExecutor
    Bitmap缩放(三)
    Bitmap缩放(二)
  • 原文地址:https://www.cnblogs.com/KongHuZi/p/13694054.html
Copyright © 2011-2022 走看看