闭包

装饰器

使用装饰函数在函数执行前和执行后分别附加额外功能

def deco(func):
    print("before myfunc() called.")
    func()
    print("  after myfunc() called.")
    return func

 

def myfunc():
    print(" myfunc() called.")

 

myfunc = deco(myfunc)


都是一样的

def deco(func):
    print("before myfunc() called.")
    func()
    print("  after myfunc() called.")
    return func

 

@deco
def myfunc():
    print(" myfunc() called.")


装饰起是把函数或者类进行专门处理的闭包,也就是把跟直接这么写相同(myfunc = deco(myfunc)) 对demo函数对输入输出进行处理,不改变原函数


闭包:

闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数

def make_adder(addend):
    def adder(augend):
        return augend + addend
    return adder

p = make_adder(23)
q = make_adder(44)

print p(100)
print q(100)
运行结果:

运行结果:

123
144



有一个特征是有配置参数,因为配置参数不同,后面再执行相同参数的函数后得到了不同的结果.这就是闭包.

闭包

函数是一个对象,所以可以作为某个函数的返回结果。

2

3

4

5

6

7

def line_conf():

    def line(x):

        return 2*x+1

    return line       # return a function object

 

my_line = line_conf()

print(my_line(5))

1

2

3

4

5

6

7

8

9

def line_conf():

    b = 15

    def line(x):

        return 2*x+b

    return line       # return a function object

 

b = 5

my_line = line_conf()

print(my_line(5))

我们可以看到,line定义的隶属程序块中引用了高层级的变量b,但b信息存在于line的定义之外 (b的定义并不在line的隶属程序块中)。我们称b为line的环境变量。事实上,line作为line_conf的返回值时,line中已经包括b的取值(尽管b并不隶属于line)。

上面的代码将打印25,也就是说,line所参照的b值是函数对象定义时可供参考的b值,而不是使用时的b值。

一个函数和它的环境变量合在一起,就构成了一个闭包(closure)。

运用:

在并行运算的环境下,我们可以让每台电脑负责一个函数,然后将一台电脑的输出和下一台电脑的输入串联起来。最终,我们像流 水线一样工作,从串联的电脑集群一端输入数据,从另一端输出数据。这样的情境最适合只有一个参数输入的函数。闭包就可以实现这一目的。






posted @ 2016-08-14 13:34  意发并行  阅读(276)  评论(0编辑  收藏  举报