码迷,mamicode.com
首页 > 编程语言 > 详细

Python--12 内嵌函数和闭包

时间:2017-09-07 19:31:14      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:oca   reference   def   style   type   err   trace   ror   rac   

内嵌函数/内部函数

  >>> 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

 

Python--12 内嵌函数和闭包

标签:oca   reference   def   style   type   err   trace   ror   rac   

原文地址:http://www.cnblogs.com/fengjunjie-w/p/7491109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!