Python装饰器实例(2):面向切面编程

1. 装饰器入门

1.1. 需求是怎么来的?

装饰器的定义非常抽象,咱们来看一个小例子。编程

1
2
3
4
def  foo():
     print  'in foo()'
 
foo()

这是一个很无聊的函数没错。可是忽然有一个更无聊的人,咱们称呼他为B君,说我想看看执行这个函数用了多长时间,好吧,那么咱们能够这样作:app

1
2
3
4
5
6
7
8
import  time
def  foo():
     start =  time.clock()
     print  'in foo()'
     end =  time.clock()
     print  'used:' , end -  start
 
foo()

很好,功能看起来无懈可击。但是蛋疼的B君此刻忽然不想看这个函数了,他对另外一个叫foo2的函数产生了更浓厚的兴趣。函数

怎么办呢?若是把以上新增长的代码复制到foo2里,这就犯了大忌了~复制什么的难道不是最讨厌了么!并且,若是B君继续看了其余的函数呢?spa

1.2. 以不变应万变,是变也

还记得吗,函数在Python中是一等公民,那么咱们能够考虑从新定义一个函数timeit,将foo的引用传递给他,而后在timeit中调用foo并进行计时,这样,咱们就达到了不改动foo定义的目的,并且,不论B君看了多少个函数,咱们都不用去修改函数定义了!.net

1
2
3
4
5
6
7
8
9
10
11
12
import  time
 
def  foo():
     print  'in foo()'
 
def  timeit(func):
     start =  time.clock()
     func()
     end = time.clock()
     print  'used:' , end -  start
 
timeit(foo)

看起来逻辑上并无问题,一切都很美好而且运做正常!……等等,咱们彷佛修改了调用部分的代码。本来咱们是这样调用的:foo(),修改之后变成了:timeit(foo)。这样的话,若是foo在N处都被调用了,你就不得不去修改这N处的代码。或者更极端的,考虑其中某处调用的代码没法修改这个状况,好比:这个函数是你交给别人使用的。code

1.3. 最大限度地少改动!

既然如此,咱们就来想一想办法不修改调用的代码;若是不修改调用代码,也就意味着调用foo()须要产生调用timeit(foo)的效果。咱们能够想到将timeit赋值给foo,可是timeit彷佛带有一个参数……想办法把参数统一吧!若是timeit(foo)不是直接产生调用效果,而是返回一个与foo参数列表一致的函数的话……就很好办了,将timeit(foo)的返回值赋值给foo,而后,调用foo()的代码彻底不用修改!对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#-*- coding: UTF-8 -*-
import  time
 
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()

这样,一个简易的计时器就作好了!咱们只须要在定义foo之后调用foo以前,加上foo = timeit(foo),就能够达到计时的目的,这也就是装饰器的概念,看起来像是foo被timeit装饰了。在在这个例子中,函数进入和退出时须要计时,这被称为一个横切面(Aspect),这种编程方式被称为面向切面的编程(Aspect-Oriented Programming)。与传统编程习惯的从上往下执行方式相比较而言,像是在函数执行的流程中横向地插入了一段逻辑。在特定的业务领域里,能减小大量重复代码。面向切面编程还有至关多的术语,这里就很少作介绍,感兴趣的话能够去找找相关的资料。ci

这个例子仅用于演示,并无考虑foo带有参数和有返回值的状况,完善它的重任就交给你了 :)get

2. Python的额外支持

2.1. 语法糖

上面这段代码看起来彷佛已经不能再精简了,Python因而提供了一个语法糖来下降字符输入量。it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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()

重点关注第11行的@timeit,在定义上加上这一行与另外写foo = timeit(foo)彻底等价,千万不要觉得@有另外的魔力。除了字符输入少了一些,还有一个额外的好处:这样看上去更有装饰器的感受。

2.2. 内置的装饰器

内置的装饰器有三个,分别是staticmethod、classmethod和property,做用分别是把类中定义的实例方法变成静态方法、类方法和类属性。因为模块里能够定义函数,因此静态方法和类方法的用处并非太多,除非你想要彻底的面向对象编程。而属性也不是不可或缺的,Java没有属性也同样活得很滋润。从我我的的Python经验来看,我没有使用过property,使用staticmethod和classmethod的频率也很是低。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class  Rabbit( object ):
     
     def  __init__( self , name):
         self ._name =  name
     
     @staticmethod
     def  newRabbit(name):
         return  Rabbit(name)
     
     @classmethod
     def  newRabbit2( cls ):
         return  Rabbit('')
     
     @property
     def  name( self ):
         return  self ._name

这里定义的属性是一个只读属性,若是须要可写,则须要再定义一个setter:

1
2
3
@name .setter
def  name( self , name):
     self ._name =  name

2.3. functools模块

functools模块提供了两个装饰器。这个模块是Python 2.5后新增的,通常来讲你们用的应该都高于这个版本。但我平时的工做环境是2.4 T-T

2.3.1. wraps(wrapped[, assigned][, updated]): 
这是一个颇有用的装饰器。看过前一篇反射的朋友应该知道,函数是有几个特殊属性好比函数名,在被装饰后,上例中的函数名foo会变成包装函数的名字wrapper,若是你但愿使用反射,可能会致使意外的结果。这个装饰器能够解决这个问题,它能将装饰过的函数的特殊属性保留。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import  time
import  functools
 
def  timeit(func):
     @functools .wraps(func)
     def  wrapper():
         start =  time.clock()
         func()
         end = time.clock()
         print  'used:' , end -  start
     return  wrapper
 
@timeit
def  foo():
     print  'in foo()'
 
foo()
print  foo.__name__

首先注意第5行,若是注释这一行,foo.__name__将是'wrapper'。另外相信你也注意到了,这个装饰器居然带有一个参数。实际上,他还有另外两个可选的参数,assigned中的属性名将使用赋值的方式替换,而updated中的属性名将使用update的方式合并,你能够经过查看functools的源代码得到它们的默认值。对于这个装饰器,至关于wrapper = functools.wraps(func)(wrapper)。

2.3.2. total_ordering(cls): 
这个装饰器在特定的场合有必定用处,可是它是在Python 2.7后新增的。它的做用是为实现了至少__lt__、__le__、__gt__、__ge__其中一个的类加上其余的比较方法,这是一个类装饰器。若是以为很差理解,不妨仔细看看这个装饰器的源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
53   def  total_ordering( cls ):
54       """Class decorator that fills in missing ordering methods"""
55       convert =  {
56           '__lt__' : [( '__gt__' , lambda  self , other: other < self ),
57                      ( '__le__' , lambda  self , other: not  other < self ),
58                      ( '__ge__' , lambda  self , other: not  self  < other)],
59           '__le__' : [( '__ge__' , lambda  self , other: other < =  self ),
60                      ( '__lt__' , lambda  self , other: not  other < =  self ),
61                      ( '__gt__' , lambda  self , other: not  self  < =  other)],
62           '__gt__' : [( '__lt__' , lambda  self , other: other > self ),
63                      ( '__ge__' , lambda  self , other: not  other > self ),
64                      ( '__le__' , lambda  self , other: not  self  > other)],
65           '__ge__' : [( '__le__' , lambda  self , other: other > =  self ),
66                      ( '__gt__' , lambda  self , other: not  other > =  self ),
67                      ( '__lt__' , lambda  self , other: not  self  > =  other)]
68       }
69       roots =  set ( dir ( cls )) & set (convert)
70       if  not  roots:
71           raise  ValueError( 'must define at least one ordering operation: < > <= >=' )
72       root =  max (roots)       # prefer __lt__ to __le__ to __gt__ to __ge__
73       for  opname, opfunc in  convert[root]:
74           if  opname not  in  roots:
75               opfunc.__name__ =  opname
76               opfunc.__doc__ =  getattr ( int , opname).__doc__
77               setattr ( cls , opname, opfunc)
78       return  cls
相关文章
相关标签/搜索