zoukankan      html  css  js  c++  java
  • 闭包

      def fun():

        pass

      obj = fun()   obj指向了内存中的函数 ,里面有函数代码,有函数名,有文档说明__doc__,'fun'字符串是函数名,obj可以看作是一个变量

      obj()   调用             

      fun()   调用 

    闭包:  1、在一个函数里定义另外一个函数

         2、里面的函数用到了外部函数的参数

         3.  返回内部函数的引用

    def out(num):

      def inner(a):

        return num+a

      return inner         返回内部函数的地址

    fun = out()  相当于调用函数out ,然而函数out的执行结果是返回内部函数的地址,所以fun 这个 变量里 就存了内部 函数 的地址。

    fun(4)就是执行内部函数   


    修改外部函数的变量

    在py3 中

    def count(start):

      def inner():

        nolocal start

        start += 1

        print(start)

      return inner

    在py2中

    def  count(start):

       start = [start]

      def inner():

        start[0] += 1

        return start[0]

     

    life is short,i need python
  • 相关阅读:
    换盘符cd的用法
    matplotlib.pyplot 属性用法
    类 __init__的注意事项
    Python File(文件) 方法
    Spyder 快捷键
    python路径引用r的含义
    VBA+SQL transform pivot union联合查询的基础应用
    Box-Cox变换
    静态字段引用的对象为什么不会被GC回收
    编译hotspot8
  • 原文地址:https://www.cnblogs.com/lvhonglei-python/p/7587014.html
Copyright © 2011-2022 走看看