Python 中的@修饰器理解

文章先由stackoverflow上面的一个问题引起吧,如果使用如下的代码:

[py]  view plain  copy
  1. @makebold  
  2. @makeitalic  
  3. def say():  
  4.    return "Hello"  

打印出如下的输出:

[py]  view plain  copy
  1. <b><i>Hello<i></b>  

你会怎么做?最后给出的答案是:

[py]  view plain  copy
  1. def makebold(fn):  
  2.     def wrapped():  
  3.         return "<b>" + fn() + "</b>"  
  4.     return wrapped  
  5.    
  6. def makeitalic(fn):  
  7.     def wrapped():  
  8.         return "<i>" + fn() + "</i>"  
  9.     return wrapped  
  10.   
  11. @makebold  
  12. @makeitalic  
  13. def hello():  
  14.     return "hello world"  
  15.    
  16. print hello() ## 返回 <b><i>hello world</i></b>  

现在我们来看看如何从一些最基础的方式来理解Python的装饰器。英文讨论参考Here

装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志、性能测试、事务处理等。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。

1.1. 需求是怎么来的?

装饰器的定义很是抽象,我们来看一个小例子。

 

[py]  view plain  copy
  1. def foo():  
  2.     print 'in foo()'  
  3. foo()  

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

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

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

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

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

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

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

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

1.3. 最大限度地少改动!

既然如此,我们就来想想办法不修改调用的代码;如果不修改调用代码,也就意味着调用foo()需要产生调用timeit(foo)的效果。我们可以想到将timeit赋值给foo,但是timeit似乎带有一个参数……想办法把参数统一吧!如果timeit(foo)不是直接产生调用效果,而是返回一个与foo参数列表一致的函数的话……就很好办了,将timeit(foo)的返回值赋值给foo,然后,调用foo()的代码完全不用修改!

[py]  view plain  copy
  1. #-*- coding: UTF-8 -*-  
  2. import time  
  3.    
  4. def foo():  
  5.     print 'in foo()'  
  6.    
  7. # 定义一个计时器,传入一个,并返回另一个附加了计时功能的方法  
  8. def timeit(func):  
  9.        
  10.     # 定义一个内嵌的包装函数,给传入的函数加上计时功能的包装  
  11.     def wrapper():  
  12.         start = time.clock()  
  13.         func()  
  14.         end =time.clock()  
  15.         print 'used:', end - start  
  16.        
  17.     # 将包装后的函数返回  
  18.     return wrapper  
  19.    
  20. foo = timeit(foo)  
  21. foo()  

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

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

上面这段代码看起来似乎已经不能再精简了,Python于是提供了一个语法糖来降低字符输入量。

[py]  view plain  copy
  1. import time  
  2.    
  3. def timeit(func):  
  4.     def wrapper():  
  5.         start = time.clock()  
  6.         func()  
  7.         end =time.clock()  
  8.         print 'used:', end - start  
  9.     return wrapper  
  10.   
  11. @timeit  
  12. def foo():  
  13.     print 'in foo()'  
  14.    
  15. foo()  

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

-------------------

要理解python的装饰器,我们首先必须明白在Python中函数也是被视为对象。这一点很重要。先看一个例子:

[py]  view plain  copy
  1. def shout(word="yes") :  
  2.     return word.capitalize()+" !"  
  3.    
  4. print shout()  
  5. # 输出 : 'Yes !'  
  6.    
  7. # 作为一个对象,你可以把函数赋给任何其他对象变量   
  8.    
  9. scream = shout  
  10.    
  11. # 注意我们没有使用圆括号,因为我们不是在调用函数  
  12. # 我们把函数shout赋给scream,也就是说你可以通过scream调用shout  
  13.    
  14. print scream()  
  15. # 输出 : 'Yes !'  
  16.    
  17. # 还有,你可以删除旧的名字shout,但是你仍然可以通过scream来访问该函数  
  18.    
  19. del shout  
  20. try :  
  21.     print shout()  
  22. except NameError, e :  
  23.     print e  
  24.     #输出 : "name 'shout' is not defined"  
  25.    
  26. print scream()  
  27. # 输出 : 'Yes !'  

我们暂且把这个话题放旁边,我们先看看python另外一个很有意思的属性:可以在函数中定义函数:

[py]  view plain  copy
  1. def talk() :  
  2.    
  3.     # 你可以在talk中定义另外一个函数  
  4.     def whisper(word="yes") :  
  5.         return word.lower()+"...";  
  6.    
  7.     # ... 并且立马使用它  
  8.    
  9.     print whisper()  
  10.    
  11. # 你每次调用'talk',定义在talk里面的whisper同样也会被调用  
  12. talk()  
  13. # 输出 :  
  14. # yes...  
  15.    
  16. # 但是"whisper" 不会单独存在:  
  17.    
  18. try :  
  19.     print whisper()  
  20. except NameError, e :  
  21.     print e  
  22.     #输出 : "name 'whisper' is not defined"*  

函数引用

从以上两个例子我们可以得出,函数既然作为一个对象,因此:

1. 其可以被赋给其他变量

2. 其可以被定义在另外一个函数内

这也就是说,函数可以返回一个函数,看下面的例子:

[py]  view plain  copy
  1. def getTalk(type="shout") :  
  2.    
  3.     # 我们定义另外一个函数  
  4.     def shout(word="yes") :  
  5.         return word.capitalize()+" !"  
  6.    
  7.     def whisper(word="yes") :  
  8.         return word.lower()+"...";  
  9.    
  10.     # 然后我们返回其中一个  
  11.     if type == "shout" :  
  12.         # 我们没有使用(),因为我们不是在调用该函数  
  13.         # 我们是在返回该函数  
  14.         return shout  
  15.     else :  
  16.         return whisper  
  17.    
  18. # 然后怎么使用呢 ?  
  19.    
  20. # 把该函数赋予某个变量  
  21. talk = getTalk()       
  22.    
  23. # 这里你可以看到talk其实是一个函数对象:  
  24. print talk  
  25. #输出 : <function shout at 0xb7ea817c>  
  26.    
  27. # 该对象由函数返回的其中一个对象:  
  28. print talk()  
  29.    
  30. # 或者你可以直接如下调用 :  
  31. print getTalk("whisper")()  
  32. #输出 : yes...  

还有,既然可以返回一个函数,我们可以把它作为参数传递给函数:

[py]  view plain  copy
  1. def doSomethingBefore(func) :  
  2.     print "I do something before then I call the function you gave me"  
  3.     print func()  
  4.    
  5. doSomethingBefore(scream)  
  6. #输出 :  
  7. #I do something before then I call the function you gave me  
  8. #Yes !  

这里你已经足够能理解装饰器了,其他它可被视为封装器。也就是说,它能够让你在装饰前后执行代码而无须改变函数本身内容。

手工装饰

那么如何进行手动装饰呢?

[py]  view plain  copy
  1. # 装饰器是一个函数,而其参数为另外一个函数  
  2. def my_shiny_new_decorator(a_function_to_decorate) :  
  3.    
  4.     # 在内部定义了另外一个函数:一个封装器。  
  5.     # 这个函数将原始函数进行封装,所以你可以在它之前或者之后执行一些代码  
  6.     def the_wrapper_around_the_original_function() :  
  7.    
  8.         # 放一些你希望在真正函数执行前的一些代码  
  9.         print "Before the function runs"  
  10.    
  11.         # 执行原始函数  
  12.         a_function_to_decorate()  
  13.    
  14.         # 放一些你希望在原始函数执行后的一些代码  
  15.         print "After the function runs"  
  16.    
  17.     #在此刻,"a_function_to_decrorate"还没有被执行,我们返回了创建的封装函数  
  18.     #封装器包含了函数以及其前后执行的代码,其已经准备完毕  
  19.     return the_wrapper_around_the_original_function  
  20.    
  21. # 现在想象下,你创建了一个你永远也不远再次接触的函数  
  22. def a_stand_alone_function() :  
  23.     print "I am a stand alone function, don't you dare modify me"  
  24.    
  25. a_stand_alone_function()  
  26. #输出: I am a stand alone function, don't you dare modify me  
  27.    
  28. # 好了,你可以封装它实现行为的扩展。可以简单的把它丢给装饰器  
  29. # 装饰器将动态地把它和你要的代码封装起来,并且返回一个新的可用的函数。  
  30. a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)  
  31. a_stand_alone_function_decorated()  
  32. #输出 :  
  33. #Before the function runs  
  34. #I am a stand alone function, don't you dare modify me  
  35. #After the function runs  

现在你也许要求当每次调用a_stand_alone_function时,实际调用却是a_stand_alone_function_decorated。实现也很简单,可以用my_shiny_new_decorator来给a_stand_alone_function重新赋值。

[py]  view plain  copy
  1. a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)  
  2. a_stand_alone_function()  
  3. #输出 :  
  4. #Before the function runs  
  5. #I am a stand alone function, don't you dare modify me  
  6. #After the function runs  
  7.    
  8. # And guess what, that's EXACTLY what decorators do !  

装饰器揭秘

前面的例子,我们可以使用装饰器的语法:

[py]  view plain  copy
  1. @my_shiny_new_decorator  
  2. def another_stand_alone_function() :  
  3.     print "Leave me alone"  
  4.    
  5. another_stand_alone_function()  
  6. #输出 :  
  7. #Before the function runs  
  8. #Leave me alone  
  9. #After the function runs  

当然你也可以累积装饰:

[py]  view plain  copy
  1. def bread(func) :  
  2.     def wrapper() :  
  3.         print "</''''''\>"  
  4.         func()  
  5.         print "<\______/>"  
  6.     return wrapper  
  7.    
  8. def ingredients(func) :  
  9.     def wrapper() :  
  10.         print "#tomatoes#"  
  11.         func()  
  12.         print "~salad~"  
  13.     return wrapper  
  14.    
  15. def sandwich(food="--ham--") :  
  16.     print food  
  17.    
  18. sandwich()  
  19. #输出 : --ham--  
  20. sandwich = bread(ingredients(sandwich))  
  21. sandwich()  
  22. #outputs :  
  23. #</''''''\>  
  24. # #tomatoes#  
  25. # --ham--  
  26. # ~salad~  
  27. #<\______/>  

使用python装饰器语法:

[py]  view plain  copy
  1. @bread  
  2. @ingredients  
  3. def sandwich(food="--ham--") :  
  4.     print food  
  5.    
  6. sandwich()  
  7. #输出 :  
  8. #</''''''\>  
  9. # #tomatoes#  
  10. # --ham--  
  11. # ~salad~  
  12. #<\______/>  

装饰器的顺序很重要,需要注意:

[py]  view plain  copy
  1. @ingredients  
  2. @bread  
  3. def strange_sandwich(food="--ham--") :  
  4.     print food  
  5.    
  6. strange_sandwich()  
  7. #输出 :  
  8. ##tomatoes#  
  9. #</''''''\>  
  10. # --ham--  
  11. #<\______/>  
  12. # ~salad~  

最后回答前面提到的问题:

[py]  view plain  copy
  1. # 装饰器makebold用于转换为粗体  
  2. def makebold(fn):  
  3.     # 结果返回该函数  
  4.     def wrapper():  
  5.         # 插入一些执行前后的代码  
  6.         return "<b>" + fn() + "</b>"  
  7.     return wrapper  
  8.    
  9. # 装饰器makeitalic用于转换为斜体  
  10. def makeitalic(fn):  
  11.     # 结果返回该函数  
  12.     def wrapper():  
  13.         # 插入一些执行前后的代码  
  14.         return "<i>" + fn() + "</i>"  
  15.     return wrapper  
  16.   
  17. @makebold  
  18. @makeitalic  
  19. def say():  
  20.     return "hello"  
  21.    
  22. print say()  
  23. #输出: <b><i>hello</i></b>  
  24.    
  25. # 等同于  
  26. def say():  
  27.     return "hello"  
  28. say = makebold(makeitalic(say))  
  29.    
  30. print say()  
  31. #输出: <b><i>hello</i></b>  

内置的装饰器

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

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

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

[py]  view plain  copy
  1. @name.setter  
  2. def name(self, name):  
  3.     self._name = name  

functools模块

functools模块提供了两个装饰器。这个模块是Python 2.5后新增的,一般来说大家用的应该都高于这个版本。但我平时的工作环境是2.4 T-T

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

[py]  view plain  copy
  1. import time  
  2. import functools  
  3.    
  4. def timeit(func):  
  5.     @functools.wraps(func)  
  6.     def wrapper():  
  7.         start = time.clock()  
  8.         func()  
  9.         end =time.clock()  
  10.         print 'used:', end - start  
  11.     return wrapper  
  12.   
  13. @timeit  
  14. def foo():  
  15.     print 'in foo()'  
  16.    
  17. foo()  
  18. 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__其中一个的类加上其他的比较方法,这是一个类装饰器。如果觉得不好理解,不妨仔细看看这个装饰器的源代码:

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

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值