(给Python开发者加星标,提升Python技能)
翻译:可乐,校对:艾凌风
发布:Python开发者(id:PythonCoder)
注意: 这是一篇 StackOverflow 上的问题回答,因为这个回答很棒,所以我把它存档了
问: 怎样在 Python 中连续使用多个函数装饰器?
如果你不想看详细的解释,你可以看 Paolo Bergantino 的回答
装饰器基础
Python 的装饰器都是对象
为了理解装饰器,你首先必须知道 Python 中的函数都是 object 对象。这非常重要。让我们通过一个例子来看看原因。
def shout(word='yes'): return word.capitalize() + '!' print shout()# outputs : 'Yes!' # 作为一个 object 对象,你可以把一个函数分配给一个变量,就像是# 其他 object 对象一样 scream = shout # 请注意我们并没有使用括号:因此我们没有调用函数,我们只是把函数 `shout` 赋值给变量 `scream`# 这意味着我们可以通过 `scream` 调用 `shout` 函数 print scream()# outputs : 'Yes!' # 除了这些,这还意味着你可以移除旧的函数名 `shout`,# 之后依然可以通过 `scream` 访问函数 del shouttry: print shout()except NameError as e: print e print scream()# outputs: 'Yes!'
记住上面的内容,一会我们还会用得到。
Python 函数另一个有趣的性质在于它们可以。。。在另一个函数内部定义!
def talk(): def whisper(word='yes'): return word.lower() + '...' print whisper() # 你可以调用 `talk` 函数,每次调用这个函数都会定义 `whisper` 函数,并且# 在 `talk` 函数中调用 `whisper` 函数 talk()# outputs: # "yes..." # 但是 `whisper` 函数在 `talk` 函数外部并不存在:
try: print whisper()except NameError as e: print e
函数引用
现在是比较有趣的部分。。。
你已经知道了函数是 object 对象。此外,函数还:
这表示 函数可以 return 另一个函数。看下面吧!☺
def getTalk(kind='shout'): def shout(word='yes'): return word.capitalize() + '!' def whisper(word='yes'): return word.lower() + '...' if kind == 'shout': return shout else: return whisper # 你该怎样使用这个奇怪的功能呢? # 调用这个函数,然后把结果赋值给一个变量 talk = getTalk() # 你可以看到 `talk` 是一个函数对象:print talk#outputs : # The object is the one returned by the function: # 这个对象是由一个函数返回的print talk()#outputs : Yes! # 如果你觉得奇怪的话,你甚至可以直接使用它print getTalk('whisper')()#outputs : yes...
但等等…还有一些内容!
如果你可以 return 一个函数,那么你也可以把函数当作参数传递:
def doSomethingBefore(func): print 'I do something before then I call the function you gave me' print func() doSomethingBefore(scream)#outputs: #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' 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() #outputs: 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()#outputs:#Before the function runs#I am a stand alone function, don't you dare modify me#After the function runs
现在,你希望每次你调用 a_stand_alone_function 的时候,实际上 a_stand_alone_function_decorated 会被调用。也就是说,这只是用 my_shiny_new_decorator 返回的函数重写了 a_stand_alone_function 函数:
a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)a_stand_alone_function()#outputs:#Before the function runs#I am a stand alone function, don’t you dare modify me#After the function runs # 你猜怎样着?这实际上就是装饰器的原理!
装饰器解密
和前面相同的例子,但是使用了装饰器语法:
@my_shiny_new_decoratordef another_stand_alone_function(): print 'Leave me alone' another_stand_alone_function() #outputs: #Before the function runs#Leave me alone#After the function runs
就是这样,装饰器就是这么简单。@decorator 只是下面形式的简写:
another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)
装饰器只是一个 pythonic 的装饰器设计模式的变种。Python 中内置了许多种传统的设计模式来简化开发过程(例如迭代器)。
当然,你可以叠加多个装饰器:
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()#outputs: --ham--sandwich = bread(ingredients(sandwich))sandwich()#outputs:#''''''\># #tomatoes## --ham--# ~salad~#
使用 Python 的装饰器语法:
@bread@ingredientsdef sandwich(food='--ham--'): print food sandwich()#outputs:#''''''\># # --ham--# ~salad~#
你设置装饰器的顺序很重要:
@ingredients@breaddef strange_sandwich(food='--ham--'): print food strange_sandwich()#outputs:##''''''\># --ham--## ~salad~
现在:是时候回答问题了。。。
现在你很容易就知道怎样回答这个问题了:
# 生成粗体(bold)的装饰器def makebold(fn): def wrapper(): return '' + fn() + '' return wrapper # 生成斜体的装饰器def makeitalic(fn): def wrapper(): return ''
+ fn() + '' return wrapper @makebold@makeitalicdef say(): return 'hello' print say() #outputs: hello # 和上面完全等价的形式def say(): return 'hello'say = makebold(makeitalic(say)) print say()
现在你该放下轻松的心态,好好看看装饰器的高级使用方法了。
把装饰器传到下一层去
把参数传递给被装饰的函数
# 这并不是黑魔法,你只是让包装器传递参数而已 def a_decorator_passing_arguments(function_to_decorate): def a_wrapper_accepting_arguments(arg1, arg2): print 'I got args! Look:', arg1, arg2 function_to_decorate(arg1, arg2) return a_wrapper_accepting_arguments # 因为当你调用装饰器返回的函数时,实际上你在调用包装器,把参数传递给包装器,这也就完成了把参数传递给装饰器函数@a_decorator_passing_argumentsdef print_full_name(first_name, last_name): print 'My name is', first_name, last_name print_full_name('Peter', 'Venkman')# outputs:#I got args! Look: Peter Venkman#My name is Peter Venkman
装饰器方法
关于 Python 的一个优点就是方法和函数本质本质上是一样的。二者唯一的区别就是方法的第一个参数是对当前对象的引用 (self)。
这意味着你可以按照同样的方式为方法创建装饰器!只要记得考虑 self 就可以了:
def method_friendly_decorator(method_to_decorate): def wrapper(self, lie): lie = lie - 3 return method_to_decorate(self, lie) return wrapper class Lucy(object): def __init__(self): self.age = 32 @method_friendly_decorator def sayYourAge(self, lie): print 'I am {0}, what did you think?'.format(self.age + lie) l = Lucy()l.sayYourAge(-3)#outputs: I am 26, what did you think?
如果你在创建通用的装饰器 — 一个适用于任何函数或者方法的装饰器,无论参数是什么 — 那么只要使用 *args, **kwargs就可以了:
def a_decorator_passing_arbitrary_arguments(function_to_decorate): def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs): print 'Do I have args?:' print args print kwargs function_to_decorate(*args, **kwargs) return a_wrapper_accepting_arbitrary_arguments @a_decorator_passing_arbitrary_argumentsdef function_with_no_argument(): print 'Python is cool, no argument here.' function_with_no_argument()#outputs#Do I have args?:#()#{}#Python is cool, no argument here. @a_decorator_passing_arbitrary_argumentsdef function_with_arguments(a, b, c): print a, b, c function_with_arguments(1,2,3)#outputs#Do I have args?:#(1, 2, 3)#{}#1 2 3 @a_decorator_passing_arbitrary_argumentsdef function_with_named_arguments(a, b, c, platypus='Why not ?'): print 'Do {0}, {1} and {2} like platypus? {3}'.format( a, b, c, platypus) function_with_named_arguments('Bill', 'Linus', 'Steve', platypus='Indeed!')#outputs#Do I have args ? :#('Bill', 'Linus', 'Steve')#{'platypus': 'Indeed!'}#Do Bill, Linus and Steve like platypus? Indeed! class Mary(object): def __init__(self): self.age = 31 @a_decorator_passing_arbitrary_arguments def sayYourAge(self, lie=-3): print 'I am {0}, what did you think?'.format(self.age + lie) m = Mary()m.sayYourAge()#outputs# Do I have args?:#(<__main__.mary object at>,)#{}#I am 28, what did you think?
把参数传递给装饰器
太棒了,现在你对于把参数传递给装饰器本身有什么看法呢?
这可能有点奇怪,因为装饰器必须接收一个函数作为参数。因此,你可能无法直接把装饰器函数作为参数传递给另一个装饰器。
在得到答案之前,让我们写一个小的例子:
# 装饰器是普通函数
def my_decorator(func): print 'I am an ordinary function' def wrapper(): print 'I am function returned by the decorator' func() return wrapper # 因此你可以在没有任何 '@' 的情况下调用它 def lazy_function(): print 'zzzzzzzz' decorated_function = my_decorator(lazy_function)#outputs: I am an ordinary function # 上面的函数输出 'I am an ordinary function' ,因为这实际上就是我们直接调用函数的结果。没什么好奇怪的。 @my_decoratordef lazy_function(): print 'zzzzzzzz' #outputs: I am an ordinary function
结果是一模一样的:my_decorator 被调用了。因此当你使用 @my_decorator 时,Python 会调用 “my_decorator” 变量所代表的函数。
这很重要!你提供的这个变量可以指向装饰器,也可以不指向。
让我们增加点难度。☺
def decorator_maker(): print 'I make decorators! I am executed only once: '+\ 'when you make me create a decorator.' def my_decorator(func): print 'I am a decorator! I am executed only when you decorate a function.' def wrapped(): print ('I am the wrapper around the decorated function. ' 'I am called when you call the decorated function. ' 'As the wrapper, I return the RESULT of the decorated function.') return func() print 'As the decorator, I return the wrapped function.' return wrapped print 'As a decorator maker, I return a decorator' return my_decorator # 让我们创建一个装饰器。本质上是一个新函数 new_decorator = decorator_maker() #outputs:#I make decorators! I am executed only once: when you make me create a decorator.#As a decorator maker, I return a decorator # 然后我们装饰下面这个函数 def decorated_function(): print 'I am the decorated function.' decorated_function = new_decorator(decorated_function)#outputs:#I am a decorator! I am executed only when you decorate a function.#As the decorator, I return the wrapped function # 调用这个函数decorated_function()#outputs:#I am the wrapper around the decorated function. I am called when you call the decorated function.#As the wrapper, I return the RESULT of the decorated function.#I am the decorated function.
没什么意料之外的事情发生。
我们再做一次上面的事情,只不过这一次取消掉所有的中间变量:
def decorated_function(): print 'I am the decorated function.'decorated_function = decorator_maker()(decorated_function)#outputs:#I make decorators! I am executed only once: when you make me create a decorator.#As a decorator maker, I return a decorator#I am a decorator! I am executed only when you decorate a function.#As the decorator, I return the wrapped function. # 最后:decorated_function() #outputs:#I am the wrapper around the decorated function. I am called when you call the decorated function.#As the wrapper, I return the RESULT of the decorated function.#I am the decorated function.
让它更短一下:
@decorator_maker()def decorated_function(): print 'I am the decorated function.'#outputs:#I make decorators! I am executed only once: when you make me create a decorator.#As a decorator maker, I return a decorator#I am a decorator! I am executed only when you decorate a function.#As the decorator, I return the wrapped function. #最后:decorated_function() #outputs:#I am the wrapper around the decorated function. I am called when you call the decorated function.#As the wrapper, I return the RESULT of the decorated function.#I am the decorated function.
你注意到了吗?我们调用了一个 @ 语法的函数!:-)
所以,回到装饰器的参数上面来。如果我们可以使用函数生成一个临时的装饰器,我们也可以把参数传递给那个函数,对吗?
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2): print 'I make decorators! And I accept arguments:', decorator_arg1, decorator_arg2 def my_decorator(func): print 'I am the decorator. Somehow you passed me arguments:', decorator_arg1, decorator_arg2 def wrapped(function_arg1, function_arg2): print ('I am the wrapper around the decorated function.\n' 'I can access all the variables\n' '\t- from the decorator: {0} {1}\n' '\t- from the function call: {2} {3}\n' 'Then I can pass them to the decorated function' .format(decorator_arg1, decorator_arg2, function_arg1, function_arg2)) return func(function_arg1, function_arg2) return wrapped return my_decorator @decorator_maker_with_arguments('Leonard', 'Sheldon')def decorated_function_with_arguments(function_arg1, function_arg2): print ('I am the decorated function and only knows about my arguments: {0}' ' {1}'.format(function_arg1, function_arg2))
decorated_function_with_arguments('Rajesh', 'Howard')#outputs:#I make decorators! And I accept arguments: Leonard Sheldon#I am the decorator. Somehow you passed me arguments: Leonard Sheldon#I am the wrapper around the decorated function. #I can access all the variables # - from the decorator: Leonard Sheldon # - from the function call: Rajesh Howard #Then I can pass them to the decorated function#I am the decorated function and only knows about my arguments: Rajesh Howard
最后得到的就是:带参数的装饰器。参数可以设置为变量:
c1 = 'Penny'c2 = 'Leslie' @decorator_maker_with_arguments('Leonard', c1)def decorated_function_with_arguments(function_arg1, function_arg2): print ('I am the decorated function and only knows about my arguments:' ' {0} {1}'.format(function_arg1, function_arg2)) decorated_function_with_arguments(c2, 'Howard')#outputs:#I make decorators! And I accept arguments: Leonard Penny#I am the decorator. Somehow you passed me arguments: Leonard Penny#I am the wrapper around the decorated function. #I can access all the variables # - from the decorator: Leonard Penny # - from the function call: Leslie Howard #Then I can pass them to the decorated function#I am the decorated function and only knows about my arguments: Leslie Howard
如你所见,你可以使用这个技巧向装饰器传递参数,就像是向普通函数传递一样。如果你愿意的话,你甚至可以使用 *args, **kwargs。但记住,装饰器只会被调用一次。只在 Python 导入脚本的时候运行。在这之后你就无法动态设置参数了。当你执行 import x 之后,函数已经被装饰了,因此之后你无法改变任何东西。
练习: 装饰一个装饰器
好的,作为奖励,我会提供你一段代码允许装饰器接收任何参数。毕竟,为了接收参数,我们会用另一个函数创建装饰器。
我们包装一下装饰器。
我们最近看到的有包装函数的还有什么呢?
对了,就是装饰器!
让我们做点有趣的事,写一个装饰器的装饰器:
def decorator_with_args(decorator_to_enhance): """ 这个函数是被用作装饰器。 它会装饰其他函数,被装饰的函数也是一个装饰器。 喝杯咖啡吧。 它允许任何装饰器接收任意个参数, 这样你就不会为每次都要考虑怎样处理而头疼了 """ def decorator_maker(*args, **kwargs): def decorator_wrapper(func): return decorator_to_enhance(func, *args, **kwargs) return decorator_wrapper return decorator_maker
可以像下面这样使用:
# 创建一个用作装饰器的函数。然后加上一个装饰器 :-) # 不要忘记,格式是 `decorator(func, *args, **kwargs)` @decorator_with_args def decorated_decorator(func, *args, **kwargs): def wrapper(function_arg1, function_arg2): print 'Decorated with', args, kwargs return func(function_arg1, function_arg2) return wrapper # 然后用全新的装饰器装饰你的函数。 @decorated_decorator(42, 404, 1024)def decorated_function(function_arg1, function_arg2): print 'Hello', function_arg1, function_arg2 decorated_function('Universe and', 'everything')#outputs:#Decorated with (42, 404, 1024) {}#Hello Universe and everything # Whoooot!
我知道,上次你有这种感觉,是在听一个人说:“在理解递归之前,你必须首先理解递归” 时。但现在,掌握了这个之后你不觉得很棒吗?
最佳实践: 装饰器
装饰器在 Python 2.4 引进,因此确保你的代码运行的 Python 版本 >=2.4
装饰器会拖慢函数调用速度。请牢记
你无法解除装饰一个函数。 (确实 有 一些技巧可以创建允许解除装饰的装饰器,但是没人会使用它们。)因此一旦函数被装饰了,所有这个函数的代码就都装饰了。
装饰器包装函数,会使得函数更难调试。 (从 Python >=2.5 有所好转;看下文。)
functools 模块在 Python 2.5 引进。模块中包含了函数 functools.wraps() ,这个函数会把被装饰函数的名字,模块名,docstring 都复制到它的包装器中。
(有趣的事情是:functools.wraps() 是个装饰器!☺)
# 至于调试,stacktrace 输出函数的 __name__def foo(): print 'foo' print foo.__name__#outputs: foo # 有了装饰器之后,有点混乱 def bar(func): def wrapper(): print 'bar' return func() return wrapper @bardef foo(): print 'foo' print foo.__name__#outputs: wrapper # `functools` 可以改善上面的情况 import functools def bar(func): @functools.wraps(func) def wrapper(): print 'bar' return func() return
wrapper @bardef foo(): print 'foo' print foo.__name__#outputs: foo
怎样使装饰器变得有用?
现在最大的问题是: 我可以用装饰器来干嘛?
装饰器看起来很酷,很强大,但有一个实用的例子就更好了。大概有 1000 种可能的例子。常见的使用方法是扩展一个外部库函数(你无法修改)的行为,或者用来调试外部库函数(你不想修改它,因为它是临时函数)。
你可以使用装饰器以 DRY(Don’t Repeat Yourself,不重复自己) 的方式扩展函数,就像这样:
def benchmark(func): """ 一个用来输出函数执行时间的装饰器 """ import time def wrapper(*args, **kwargs): t = time.clock() res = func(*args, **kwargs) print func.__name__, time.clock()-t return res return wrapper def logging(func): """ 一个用来记录脚本活动的装饰器。 (实际上只是打印出来,但可以输出到日志!) """ def wrapper(*args, **kwargs): res = func(*args, **kwargs) print func.__name__, args, kwargs return res return wrapper def counter(func): """ 一个用来统计并输出函数执行次数的装饰器 """ def wrapper(*args, **kwargs): wrapper.count = wrapper.count + 1 res = func(*args, **kwargs) print '{0} has been used: {1}x'.format(func.__name__, wrapper.count) return res wrapper.count = 0 return wrapper @counter@benchmark@loggingdef reverse_string(string): return str(reversed(string)) print reverse_string('Able was I ere I saw Elba')print reverse_string('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!') #outputs:#reverse_string ('Able was I ere I saw Elba',) {}#wrapper 0.0#wrapper has been used: 1x #ablE was I ere I saw elbA#reverse_string ('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!',) {}#wrapper 0.0#wrapper has been used: 2x#!amanaP :lanac a ,noep a ,stah eros ,raj a ,hsac ,oloR a ,tur a ,mapS ,snip ,eperc a ,)lemac a ro( niaga gab ananab a ,gat a ,nat a ,gab ananab a ,gag a ,inoracam ,elacrep ,epins ,spam ,arutaroloc a ,shajar ,soreh ,atsap ,eonac a ,nalp a ,nam A
当然,装饰器的优点就在于你可以在不重写函数的前提下,使用在几乎任何函数上。DRY(Don’t Repeat Yourself,不要重复你自己),正如我说的:
@counter@benchmark
@loggingdef get_random_futurama_quote(): from urllib import urlopen result = urlopen('http://subfusion.net/cgi-bin/quote.pl?quote=futurama').read() try: value = result.split('
')[1].split('
')[0] return value.strip() except: return 'No, I’m ... doesn’t!' print get_random_futurama_quote()print get_random_futurama_quote() #outputs:#get_random_futurama_quote () {}#wrapper 0.02#wrapper has been used: 1x#The laws of science be a harsh mistress.#get_random_futurama_quote () {}#wrapper 0.01#wrapper has been used: 2x#Curse you, merciful Poseidon!
Python 本身提供了几种装饰器:property ,staticmethod,等
Django 使用装饰器来管理缓存,查看权限。
Twisted 用它来伪造内联异步函数调用。
装饰器的用途确实很广。
觉得本文对你有帮助?请分享给更多人
关注「Python开发者」加星标,提升Python技能

好文章,我在看❤️