Python闭包

Python闭包

闭包叫lexical closure(词法闭包),指函数及相关的环境所组成的整体。内部的称为函数,外部的称为环境,外层给内层函数提供一个运行环境。

如例1中f1的主要目的是为f2提供运行环境。

在函数内部定义一个子函数,该子函数并未被调用,而是直接作为一个返回值返回,从而达到闭合函数的效果,称为Python闭合函数。

具备变量公用、隐藏状态、函数对象和作用域随意切换、一个函数实现多种功能的特性

例1:

In [1]: def f1():

  ...:    x = 666

  ...:    def f2():

  ...:        y = "hello world"

  ...:        print x,y

  ...:    return f2

In [2]: f1()

Out[2]:

In [3]: a1 = f1()

In [4]: type(a1)

Out[4]: function

In [5]: a1()

666 hello world

例2:

In [1]: def f1(x):

  ...:    def f2(y):

  ...:        return x ** y

  ...:    return f2

In [2]: f1(4)

Out[2]:

In [3]: f4 = f1(4)

In [4]: type(f4)

Out[4]: function

In [5]: f4(1)

Out[5]: 4

In [6]: f4(2)

Out[6]: 16

In [7]: f4(3)

Out[7]: 64

In [8]: f4 = f1(3)

In [9]: f4(1)

Out[9]: 3

In [10]: f4(2)

Out[10]: 9

In [11]: f4(3)

Out[11]: 27

例3:构建函数,使其在给定起始位置,能给出轨迹改变后的位置

In [1]: def startPos(x,y):

  ...:    def newPos(m,n):

  ...:        print "The start position is (%d,%d) ,The new position is (%d,%d)."% (x,y,x+m,y+n)

  ...:    return newPos

In [2]: action = startPos(10,10)

In [3]: action(-2,12)

The start position is (10,10) ,The new position is(8,22).

In [4]: action(8,12)

The start position is (10,10) ,The new position is(18,22).

In [5]: action = startPos(18,22)

In [6]: action(8,12)

The start position is (18,22) ,The new position is(26,34).

发布了108 篇原创文章 · 获赞 47 · 访问量 48万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章