• Python中的函数对象与闭包


    函数在Python中是第一类对象,可以当做参数传递给其他函数,放在数据结构中,以及作为函数的返回结果。

    下面的例子为接受另外一个函数作为输入并调用它

    1 #foo.py
    2 def callf(func):
    3     return func()

    使用上面的函数:

    1 import foo
    2 def helloworld():
    3     return 'Hello,World'
    4 
    5 print foo.callf(helloworld)

    >>>‘Hello,World’

    2.把函数当做数据处理时,它将显示地携带与定义该函数的周围环境相关的信息。

    将组成函数的语句和这些语句的执行环境打包在一起时,得到的对象称为闭包

    1 #foo.py
    2 x=42
    3 def callf(func):
    4     return func()

    使用嵌套函数时,闭包将捕捉内部函数执行所需的整个环境

    1 import foo
    2 def bar():
    3     x=13
    4     def helloWorld():
    5         return 'Hello World. x is %d '%x
    6 print  foo.callf(helloWorld)

    >>>Hello World. x is 13

     闭包实践:

    1 def a(number):
    2     def b(x):
    3         return number+x
    4     return b
    5 abc=a(5)
    6 print abc(2)
    7 >>>7

    函数b形成以闭包,number为自由变量,当函数a销毁的时候,自由变量number因为被b调用的原因,依旧存在。

    使用百度的一句话就是:闭包,子函数可以使用父函数中的局部变量,这种行为就叫做闭包!

  • 相关阅读:
    Android List 排序
    Android Connection refused
    动态代理
    Java内存模型
    面试题整理
    检查结果
    单例模式
    2019年面试记录
    面试题目
    滑动窗口的最大值
  • 原文地址:https://www.cnblogs.com/liyiran/p/4209603.html
Copyright © 2020-2023  润新知