且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python闭包以及装饰器

更新时间:2022-05-11 18:04:58

通俗的定义:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)。它只不过是个“内层”的函数,由一个名字(变量)来指代,而这个名字(变量)对于“外层”包含它的函数而言,是本地变量;

 1 #示例一:
 2 #!/usr/bin/python 
 3 #encoding=utf-8 
 4 
 5 def add_a(num1):
 6     print "num1:%d" % num1 
 7     def add_b(num2):
 8         print "num2: %d" % num2
 9         return num1 + num2 
10     return add_b        #返回的是函数名
11 
12 v = add_a(100)
13 
14 print v 
15 print v(20)
16 #执行结果:
17 root@u163:~/cp163/python# python bibao2.py 
18 num1:100
19 <function add_b at 0x7f67482a35f0>
20 num2: 20
21 120
22 
23 #示例二
24 #!/usr/bin/python 
25 #encoding=utf-8
26 
27 def  makecounter(name):
28     count = [0] 
29     def counter():
30         count[0] += 1
31         print "hello",name,':', str(count[0])+" access!"
32     return  counter
33 
34 test = makecounter("world")
35 print test   #<function counter at 0x7f9d2ece57d0>
36 test()
37 test()
38 test()
39 
40 #执行结果:
41 root@u163:~/cp/python# python close_pkg_demo.py
42 <function counter at 0x7f102c9497d0>
43 hello world : 1 access!
44 hello world : 2 access!
45 hello world : 3 access!

装饰器:

#!/usr/bin/python 
#encoding=utf-8

"""
def foo():
    print 'in foo()'

# 定义一个计时器,传入一个,并返回另一个附加了计时功能的方法'
def  timeit(func):
    # 定义一个内嵌的包装函数,给传入的函数加上计时功能的包装
    def  wrapper():
        start = time.clock()
        func()
        end = time.clock()
        print 'used: ', end -start
    #将包装后的函数返回
    return  wrapper

#将源函数修饰之后返回
foo = timeit(foo)
foo()
"""

#Python中内置的装饰器有三个: staticmethod、classmethod 和property
#"""使用语法糖来精简代码
import time 
def timeit(func):
    def wrapper():
        start = time.clock()
        func()
        end = time.clock()
        print "used: ", end - start
    return wrapper

@timeit
def foo():
    print "in foo()"

foo()   #相当于1、先修饰函数(foo = timeit(foo) ), 2、再执行修饰之后的函数 
#"""
#执行结果:
root@u163:~/cp/python# python deco_demo.py 
in foo()
used:  7.4e-05