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

    闭包

    闭包使局部变量在函数外背访问成为可能,return函数不加括号返回的是地址。

    函数作为返回值

    高阶函数除了可以接受函数作为参数外,还可以把函数做为结果返回。

    返回结果的实例:

    def sum(*args)#*args代表着 函数的参数的数目是可变

      ax = o

      for n in args:

        ax = ax + n

      return ax

    f = sum(1,2,3)

    print(f)

    输出结果为:6

    返回函数实例:

    def sum(*args):

      def return_sum():

        ax = 0

        for n in args:

          ax = ax + n

        return ax

      return return_sum#返回的是函数,而不是运行的结果

    f  = sum(1,2,3)

    print(f())

    当我们调用sum()时,返回的并不是运行结果而是求和函数

    只有当我们调用函数f()时,才是真正在计算求和的值

    牢记当return返回一个函数时,该函数并未被执行,返回函数中不要引用可能会变化的变量。

    笨鸟先飞
  • 相关阅读:
    Map
    Enumeration输出
    iterator的基本用法
    Annotation整合工厂设计模式
    自定义Annotation
    Annotation
    动态代理设计模式
    静态代理设计模式
    自定义ClassLoader
    获取类的类对象的几种方式
  • 原文地址:https://www.cnblogs.com/zoutingrong/p/11927376.html
Copyright © 2011-2022 走看看