Python--12 内嵌函数和闭包

内嵌函数/内部函数

  >>> def fun1():
  ... print('fun1()正在调用')
  ... def fun2():
  ... print('fun2()正在被调用')
  ... fun2()
  ...
  >>> fun1()
  fun1()正在调用
  fun2()正在被调用

内部函数作用域在外部函数之内

  >>> fun2()
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  NameError: name 'fun2' is not defined

闭包 closure

 闭包函数式编程的一种重要语法结构  

 函数式编程是一种编程范式,对代码进行抽象提炼和概括,使代码重用性变高

 python闭包在表现形式表现为 如果在一个内部函数里对外部作用域(但不是全局作用域)的变量进行引用,内部函数就被认为是闭包 

  >>> def FunX(x):
  ... def FunY(y):
  ... return x * y
  ... return FunY
  ...
  >>> i = FunX(8)
  >>> i
  <function FunX.<locals>.FunY at 0x7f5f41b05b70>
  >>> type(i)
  <class 'function'>
  >>> i(5)
  40
  >>> FunX(8)(5)
  40
  >>> FunY(5)
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  NameError: name 'FunY' is not defined

 

 

  >>> def Fun1():
  ... x=5
  ... def Fun2():
  ... x *= x
  ... return x
  ... return Fun2()
  ...
  >>> Fun1()
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in Fun1
  File "<stdin>", line 4, in Fun2
  UnboundLocalError: local variable 'x' referenced before assignment

 列表没有存放在栈里

  >>> def Fun1():
  ... x = [5]
  ... def Fun2():
  ... x[0] *= x[0]
  ... return x[0]
  ... return Fun2()
  ...
  >>> Fun1()
  25

nonlocal 关键字

  >>> def Fun1():
  ... x=5
  ... def Fun2():
  ... nonlocal x
  ... x *= x
  ... return x
  ... return Fun2()
  ...
  >>> Fun1()
  25

 

posted @ 2017-09-07 18:10  110528844  阅读(213)  评论(0编辑  收藏  举报