[转载]理解Python中的装饰器
首先声明:这是一篇转载的文章,原文地址:
www.cnblogs.com/rollenholt/archive/2012/05/02/2479833.html
文章先由stackoverflow上面的一个问题引起吧,如果使用如下的代码:
@makebold@makeitalicdef say(): return "Hello"
<b><i>Hello<i></b>
def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def makeitalic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped @makebold@makeitalicdef hello(): return "hello world" print hello() ## 返回 <b><i>hello world</i></b>
def foo(): print 'in foo()'foo()
import timedef foo(): start = time.clock() print 'in foo()' end = time.clock() print 'used:', end - start foo()
import time def foo(): print 'in foo()' def timeit(func): start = time.clock() func() end =time.clock() print 'used:', end - start timeit(foo)
#-*- 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()
import time def timeit(func): def wrapper(): start = time.clock() func() end =time.clock() print 'used:', end - start return wrapper @timeitdef foo(): print 'in foo()' foo()
def shout(word="yes") : return word.capitalize()+" !" print shout()# 输出 : 'Yes !' # 作为一个对象,你可以把函数赋给任何其他对象变量 scream = shout # 注意我们没有使用圆括号,因为我们不是在调用函数# 我们把函数shout赋给scream,也就是说你可以通过scream调用shout print scream()# 输出 : 'Yes !' # 还有,你可以删除旧的名字shout,但是你仍然可以通过scream来访问该函数 del shouttry : print shout()except NameError, e : print e #输出 : "name 'shout' is not defined" print scream()# 输出 : 'Yes !'
def talk() : # 你可以在talk中定义另外一个函数 def whisper(word="yes") : return word.lower()+"..."; # ... 并且立马使用它 print whisper() # 你每次调用'talk',定义在talk里面的whisper同样也会被调用talk()# 输出 :# yes... # 但是"whisper" 不会单独存在: try : print whisper()except NameError, e : print e #输出 : "name 'whisper' is not defined"*
def getTalk(type="shout") : # 我们定义另外一个函数 def shout(word="yes") : return word.capitalize()+" !" def whisper(word="yes") : return word.lower()+"..."; # 然后我们返回其中一个 if type == "shout" : # 我们没有使用(),因为我们不是在调用该函数 # 我们是在返回该函数 return shout else : return whisper # 然后怎么使用呢 ? # 把该函数赋予某个变量talk = getTalk() # 这里你可以看到talk其实是一个函数对象:print talk#输出 : <function shout at 0xb7ea817c> # 该对象由函数返回的其中一个对象:print talk() # 或者你可以直接如下调用 :print getTalk("whisper")()#输出 : yes...
def doSomethingBefore(func) : print "I do something before then I call the function you gave me" print func() doSomethingBefore(scream)#输出 :#I do something before then I call the function you gave me#Yes !
# 装饰器是一个函数,而其参数为另外一个函数def my_shiny_new_decorator(a_function_to_decorate) : # 在内部定义了另外一个函数:一个封装器。 # 这个函数将原始函数进行封装,所以你可以在它之前或者之后执行一些代码 def the_wrapper_around_the_original_function() : # 放一些你希望在真正函数执行前的一些代码 print "Before the function runs" # 执行原始函数 a_function_to_decorate() # 放一些你希望在原始函数执行后的一些代码 print "After the function runs" #在此刻,"a_function_to_decrorate"还没有被执行,我们返回了创建的封装函数 #封装器包含了函数以及其前后执行的代码,其已经准备完毕 return the_wrapper_around_the_original_function # 现在想象下,你创建了一个你永远也不远再次接触的函数def a_stand_alone_function() : print "I am a stand alone function, don't you dare modify me" a_stand_alone_function()#输出: I am a stand alone function, don't you dare modify me # 好了,你可以封装它实现行为的扩展。可以简单的把它丢给装饰器# 装饰器将动态地把它和你要的代码封装起来,并且返回一个新的可用的函数。a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)a_stand_alone_function_decorated()#输出 :#Before the function runs#I am a stand alone function, don't you dare modify me#After the function runs
a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)a_stand_alone_function()#输出 :#Before the function runs#I am a stand alone function, don't you dare modify me#After the function runs # And guess what, that's EXACTLY what decorators do !
@my_shiny_new_decoratordef another_stand_alone_function() : print "Leave me alone" another_stand_alone_function()#输出 :#Before the function runs#Leave me alone#After the function runs
def bread(func) : def wrapper() : print "</''''''\>" func() print "<\______/>" return wrapper def ingredients(func) : def wrapper() : print "#tomatoes#" func() print "~salad~" return wrapper def sandwich(food="--ham--") : print food sandwich()#输出 : --ham--sandwich = bread(ingredients(sandwich))sandwich()#outputs :#</''''''\># #tomatoes## --ham--# ~salad~#<\______/>
@bread@ingredientsdef sandwich(food="--ham--") : print food sandwich()#输出 :#</''''''\># #tomatoes## --ham--# ~salad~#<\______/>
@ingredients@breaddef strange_sandwich(food="--ham--") : print food strange_sandwich()#输出 :##tomatoes##</''''''\># --ham--#<\______/># ~salad~
# 装饰器makebold用于转换为粗体def makebold(fn): # 结果返回该函数 def wrapper(): # 插入一些执行前后的代码 return "<b>" + fn() + "</b>" return wrapper # 装饰器makeitalic用于转换为斜体def makeitalic(fn): # 结果返回该函数 def wrapper(): # 插入一些执行前后的代码 return "<i>" + fn() + "</i>" return wrapper @makebold@makeitalicdef say(): return "hello" print say()#输出: <b><i>hello</i></b> # 等同于def say(): return "hello"say = makebold(makeitalic(say)) print say()#输出: <b><i>hello</i></b>
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
@name.setterdef name(self, name): self._name = name
import timeimport functools def timeit(func): @functools.wraps(func) def wrapper(): start = time.clock() func() end =time.clock() print 'used:', end - start return wrapper @timeitdef foo(): print 'in foo()' foo()print foo.__name__
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__ = opname76 opfunc.__doc__ = getattr(int, opname).__doc__77 setattr(cls, opname, opfunc)78 return cls