Python Decorators 装饰器

  • Summary
  • 什么是装饰器
  • 带参数的装饰器
  • 串接装饰器

Summary

给原先的函数加其它的功能

1 什么是装饰器

装饰器就是修改其他函数或类(返回该函数或类)的一个函数。 理解装饰器的关键是理解闭包。之前的文章中介绍过闭包。

使用装饰器时,当解释器到达被装饰的函数时,它直接编译成

some_func = decoratr(some_func)

2 带参数的装饰器

from functools import wraps

def argumentative_decorator(gift):
    def func_wrapper(func):
        @wraps(func)
        def returned_wrapper(*args, **kwargs):
             print "I don't like this " + gift + "you gave me!"
             return func(gift, *args, **kwargs)
        return returned_wrapper
    return func_wrapper

@argumentative_decorator("sweater")
def grateful_function(gift):
    print "I love the " + gift + "!Thank you!"

grateful_function()
# >> I don't like this sweater you gave me!
# >> I love the sweater! Thank you!

实际上,它等效于:

grateful_func = argumentative_dec("sweater")(grateful_func)

因为 argumetative_dec(“sweater”) 返回了 func_wrapper.

3 串接装饰器

print_name('Sam')
@logging_decorator
def some_function():
    print "I'm the wrapped function!"

some_function()
# >> My name is Sam
# >> The function I modify has been called 1 time(s).
# >> I'm the wrapped function!

你可能感兴趣的:(Python Decorators 装饰器)