zoukankan      html  css  js  c++  java
  • Python闭包实践

    1 def multiplier(factor):
    2     def multiplyByFactor(number):
    3         return (number+1)*factor
    4     return multiplyByFactor
    5 
    6 double = multiplier(2)
    7 print double(5)
    8 
    9 print multiplier(2)(5)

    输出都是12

    闭包:把函数作为参数传递给其他函数,放在数据结构中,作为函数的返回结果。

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

    1 #foo.py
    2 x=42
    3 def callf(func):
    4     return func()
    1 import foo
    2 x = 37
    3 def helloworld():
    4     return "Hello World. x is %d" % x
    5 
    6 foo.callf(helloworld)

    调用结果为 'Hello World. x is 37'

    即helloworld()使用的x的值是在与它相同的环境中定义的。

    闭包有什么用:

    惰性求值 || 延迟求值 || 在一系列函数调用中保持某个状态

    闭包会捕捉内部函数的环境,因为可用于包装现有函数。

  • 相关阅读:
    详解objc_msgSend
    shell变量类型
    web ssh vnc备忘录
    内存对齐
    vim ctags
    vim csupport 代码 快捷键
    程序在内存中的地址映射
    nginx+php配置
    tmux 复制
    sqlite insert select 联合使用
  • 原文地址:https://www.cnblogs.com/mess4u/p/2735468.html
Copyright © 2011-2022 走看看