zoukankan      html  css  js  c++  java
  • python函数的闭包

    ---恢复内容开始---

    python允许有内部函数,也就是说可以在函数内部再定义一个函数,这就会产生变量的访问问题,类似与java的内部类,在java里内部类可以直接访问外部类的成员变量和方法,不管是否私有,但外部类需要通过内部类的引用来进行访问。python内部函数和外部函数的成员变量可以相互访问但是不能修改,也就是所谓的闭包。举个例子

     1 def outt():
     2     x=10
     3     def inn():
     4         x+=1
     5         return  x
     6     return inn()
     7         
     8 outt()
     9 Traceback (most recent call last):
    10   File "<input>", line 1, in <module>
    11   File "<input>", line 6, in outt
    12   File "<input>", line 4, in inn
    13 UnboundLocalError: local variable 'x' referenced before assignment

    可以使用nonlocal 关键字修饰外部的成员变量使其可以被修改,具体如下

     1 def outt():
     2     x=10
     3     def inn():
     4         nonlocal x
     5         x+=1
     6         return  x
     7     return inn()
     8         
     9 outt()
    10 11

    对于传的参数外函数和内函数也是闭包的 举例如下

     1 def outt():
     2     x=10
     3     def inn(y):
     4         nonlocal x
     5         x+=y
     6         return  x
     7     return inn(y)
     8         
     9 outt()(10)
    10 Traceback (most recent call last):
    11   File "<input>", line 1, in <module>
    12   File "<input>", line 7, in outt
    13 NameError: global name 'y' is not defined

    但是可以简化写法避免传参问题

     1 def outt():
     2     x=10
     3     def inn(y):
     4         nonlocal x
     5         x+=y
     6         return  x
     7     return inn
     8         
     9 outt()(10)
    10 20

    可以看出外函数调用内函数时没有在括号里传参python可以对他进行默认的赋值操作,这样就避免了参数在两个函数之间的传递问题

  • 相关阅读:
    IntelliJ IDEA 常用快捷键和设置
    Code Project精彩系列(2)
    Code Project精彩系列(2)
    Code Project精彩系列(2)
    Apache和Tomcat区别
    Apache和Tomcat区别
    Apache和Tomcat区别
    如何在 GitHub 建立个人主页和项目演示页面
    如何在 GitHub 建立个人主页和项目演示页面
    如何在 GitHub 建立个人主页和项目演示页面
  • 原文地址:https://www.cnblogs.com/ymzh/p/8366346.html
Copyright © 2011-2022 走看看