python函数中闭包的概念说明

函数中闭包的概念说明

闭包:
  内层函数对外层函数非全局变量的引用,就叫做闭包


判断闭包方法 ._closure_ :

  执行后返回有效信息就是闭包,返回none就不是闭包

    举例1: 是闭包
      def wrapper():
      name = 'alex'
      def inner():
      print(name)
      inner()
      print(inner.__closure__) #(<cell at 0x006121D0: str object at 0x00227380>,)
      wrapper()
    结果:

      alex
      <cell at 0x006121D0: str object at 0x00227380>

  
    举例2: 不是闭包
      name = 'alex'

      def wrapper():
      def inner():
      print(name)
      inner()
      print(inner.__closure__) # None
      wrapper()
    结果:
      alex
      None

闭包的作用:

  闭包的特殊机制:
    python解释器遇到了闭包,闭包一个特殊机制是闭包不会随着函数的结束而释放。即函数运行完成后这个闭包的临时空间不会释放。
    或者说函数结束后,该函数向上层引用的非全局变量仍然还是存在的不会被清空。
    引用的非全局变量不关闭,仍在内存中,再次使用时候直接从该内存里调用。

  闭包的用途:
    爬虫
    装饰器

      爬虫举例:
        def index():
        url = "http://www.xiaohua100.cn/index.html"
        def get():
        return urlopen(url).read()
        return get

        xiaohua = index() # get
        content = xiaohua()
        content1 = xiaohua()
        content2 = xiaohua()
        print(content.decode())

猜你喜欢

转载自www.cnblogs.com/liujiyu/p/9105768.html