前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python每日一题:装饰器(完整篇)

Python每日一题:装饰器(完整篇)

作者头像
用户7685359
发布2020-08-22 18:07:31
9700
发布2020-08-22 18:07:31
举报
文章被收录于专栏:FluentStudyFluentStudyFluentStudy

装饰器基础

一、函数是对象

要理解装饰器,你首先必须要知道在Python中,函数是对象。这一点对装饰器有着很重要的影响。让我们用一个简单的例子来看一下为什么:

def shout(word="yes"):
    return word.capitalize()+"!"
print(shout())
# 输出 : 'Yes!'
# 因为函数是一个对象,所以你可以像其他任何对象一样,将它赋值给另一个变量
scream = shout
# 注意,在赋值时,我们并没有使用括号(),即表示我们并没有在调用函数
# 我们只是将 "shout" 赋值给了变量 "scream"
# 通过赋值的操作意味着你可以通过调用 scream() 来达到调用 shout()的目的
print(scream())
# 输出 : 'Yes!'
# 更重要的是,你可以移除旧的函数名 "shout"
# 而这个函数仍然可以通过 screac() 来进行调用
del shout
try:
    print(shout())
except NameError, e:
    print(e)
    #输出: "name 'shout' is not defined"
print(scream())
# 输出: 'Yes!'

牢记这一点,我们过会将会回到这一点上。

对Python中的函数而言,另外一个有趣的特点就是在函数体内也可以定义函数。

def talk():
    # 你可以在 talk() 中定义一个函数
    def whisper(word="yes"):
        return word.lower()+"..."
    # 并且很快的调用它
    print(whisper())
# 你可以调用 "talk",每调用 "talk" 都会定义一次 "whisper"
# 而 "whisper" 在 "talk" 的函数体中被调用
talk()
# 输出: 
# "yes..."
# 但是 "whisper" 在 "talk" 外是不存在的
try:
    print(whisper())
except NameError, e:
    print(e)
    #输出 : "name 'whisper' is not defined"*
    #Python's functions are objects
二、函数引用

好了,你还在坚持看吗?现在到了有趣的部分了…

从上面,你已经知道了,Python中的函数是对象,因此,函数有如下两个特点:

  1. 可以赋值给另一个变量
  2. 可以定义在另一个函数中

这意味着一个函数可以作为另一个函数的返回值。

def getTalk(kind="shout"):
    # 在内部动态定义两个函数
    # 这里需要注意的是 on the fly 的翻译,我查了下,在计算机中,可理解为动态生成的。
    def shout(word="yes"):
        return word.capitalize()+"!"
    def whisper(word="yes") :
        return word.lower()+"...";
    # 然后返回其中一个
    if kind == "shout":
        # 没有使用 "()",即表示并没有调用函数
        # 返回函数对象
        return shout  
    else:
        return whisper
# 我们如何使用这个奇怪的特点
# 调用函数并且把它赋值给一个变量
talk = getTalk()      
# You can see that "talk" is here a function object:
# 你可以看到,这里的 "talk" 已经是一个函数对象
print(talk)
#输出 : <function shout at 0xb7ea817c>
# The object is the one returned by the function:
# 这个对象是 getTalk() 函数返回的一人对象
print(talk())
#输出 : Yes!
# 简单点,你也可以直接调用进行打印输出
print(getTalk("whisper")())
#输出 : yes...

还有更多别的用法!

如果你可以将函数作为返回值返回,那么函数同样也可以另外一个函数的参数

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!

好了,你现在做好了理解装饰器的准备知识。可以看到装饰器就是 "wrappers",装饰器可以让你在原来函数的代码之前和之前执行代码,并且不会修改原来函数本身。

三、手写装饰器

你会如何手动实现装饰器呢:

# 一个装饰器就是一个函数,它要求另一个函数作为参数
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_decorate" 还没有被执行
    # 我们返回了刚创建的包装器函数
    # 这个包装器包括了被包装函数以及在它之前和之前要执行的代码。现在它已经准备好被使用了!
    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时,都会调用a_stand_alone_function_修饰。这很简单,只需用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_decorator
def 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)

装饰器只是装饰器设计模式的Python变体。在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
@ingredients
def sandwich(food="--ham--"):
    print(food)
sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>

你设置装饰器的顺序也很重要:

@ingredients
@bread
def strange_sandwich(food="--ham--"):
    print(food)
strange_sandwich()
#outputs:
##tomatoes#
#</''''''\>
# --ham--
#<\______/>
# ~salad~

好了,现在来回答问题…

综上所述,你可以简单看看如何来回答这个问题:

# 用装饰器实现 加粗 效果
def makebold(fn):
    # 装饰器返回一个新的方法
    def wrapper():
        # 在原有代码之前和之后插入代码
        return "<b>" + fn() + "</b>"
    return wrapper
# 用装饰器实现 斜体 效果
def makeitalic(fn):
    # 装饰器返回一个新的方法
    def wrapper():
        # 在原有代码之前和之后插入代码
        return "<i>" + fn() + "</i>"
    return wrapper
@makebold
@makeitalic
def say():
    return "hello"
print(say())
#outputs: <b><i>hello</i></b>
# 前面几句等价于:
def say():
    return "hello"
say = makebold(makeitalic(say))
print(say())
#outputs: <b><i>hello</i></b>

看到这,你可以很愉快地离开,或者你也可以选择牺牲一点脑力来看一下装饰器进阶的知识。

装饰器进阶

一、向装饰器函数里传入参数
# 它不是一种黑魔法,你只需要让包装器中能传入参数
def a_decorator_passing_arguments(function_to_decorate):
    def a_wrapper_accepting_arguments(arg1, arg2):
        print("I got args! Look: {0}, {1}".format(arg1, arg2))
        function_to_decorate(arg1, arg2)
    return a_wrapper_accepting_arguments
# 当你调用装饰器返回的函数时
# 实际上你在调用包装器,向包装器中传入参数即向装饰函数中传入参数
@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
    print("My name is {0} {1}".format(first_name, last_name))
print_full_name("Peter", "Venkman")
# outputs:
#I got args! Look: Peter Venkman
#My name is Peter Venkman
二、装饰方法

一件很有意思的事情是在Python中,方法与函数实际上是相同的。唯一的区别是方法要求第一个参数是指向当前的对象self。(也就是说方法就是类中的定义的方法,它的第一个参数是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):
    # 用*args,**kwargs,包装器可以接受任何参数
    def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
        print("Do I have args?:")
        print(args)
        print(kwargs)
        # 然后你可以解包参数 *args **kwargs
        # 如果你不理解解包,可以参考如下链接
        # http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
        function_to_decorate(*args, **kwargs)
    return a_wrapper_accepting_arbitrary_arguments
@a_decorator_passing_arbitrary_arguments
def 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_arguments
def 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_arguments
def 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): # You can now add a default value
        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 0xb7d303ac>,)
#{}
#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_decorator
def 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
# Let’s create a decorator. It’s just a new function after all.
# 让我们使用 decorator_maker 创建一个装饰器。实际上它就是新的函数
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
# Then we decorate the function
# 然后,我们用它来装饰一个函数
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
# Let’s call the 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.
# Finally:
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.
#Eventually: 
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: {0}, {1}".format(decorator_arg1, decorator_arg2))
    def my_decorator(func):
        # The ability to pass arguments here is a gift from closures.
        # 这里可以使用外部的参数是因为闭包
        # If you are not comfortable with closures, you can assume it’s ok,
        # or read: https://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
        print("I am the decorator. Somehow you passed me arguments: {0}, {1}".format(decorator_arg1, decorator_arg2))
        # Don't confuse decorator arguments and function arguments!
        # 不要混淆装饰器的参数和函数参数
        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 know about my arguments: Leslie Howard

可以看见,我们可以使用一些小技术给装饰器传入参数,就像给普通的函数传递参数一样。你甚至可以使用 args,*kwargs。但是请记住,装饰器只会在第一次引入时被调用,之后不能再动态地设置它的参数。当你执行 import x 时,函数已经被修饰过了,所以不能再做任何的修改。

五、练习:装饰一个装饰器

好的,作为奖励,我将给出一个代码片段,让任何装饰器能接受通用的参数。毕竟,我们为了让装饰器参接受参数,我们使用了另一外函数去创建它。

即我们包装了装饰器。

我们最近看到的那个包装函数还有什么?

是的,装饰器!

让我们找点乐子,为装饰器写一个装饰器

def decorator_with_args(decorator_to_enhance):
    """ 
    这个函数用于作装饰器
    它必须用来装饰其他函数
    它将允许任何的装饰器可以接受任意数量的参数
    This function is supposed to be used as a decorator.
    It must decorate an other function, that is intended to be used as a decorator.
    Take a cup of coffee.
    It will allow any decorator to accept an arbitrary number of arguments,
    saving you the headache to remember how to do that every time.
    """
    # We use the same trick we did to pass arguments
    # 我们使用同样的技巧去传递参数
    def decorator_maker(*args, **kwargs):
        # 我们动态地创建了一个只接受一个函数作为参数的装饰器
        # 但保留着从创建者中传递进来的参数
        # We create on the fly a decorator that accepts only a function
        # but keeps the passed arguments from the maker.
        def decorator_wrapper(func):
            # 我们返回最外层装饰器的结果(相当于执行被装饰的装饰器装饰的函数)
            # 毕竟它只是一个普通的函数(只是返回值也是一个函数)
            # 唯一的陷阱:装饰器必须指定返回函数名,和参数一致,否则它不会工作:(这里不是特别理解它指的遗憾是什么)
            # We return the result of the original decorator, which, after all, 
            # IS JUST AN ORDINARY FUNCTION (which returns a function).
            # Only pitfall: the decorator must have this specific signature or it won't work:
            return decorator_to_enhance(func, *args, **kwargs)
        return decorator_wrapper
    return decorator_maker

你可以像下面这样使用它:

# You create the function you will use as a decorator. And stick a decorator on it :-)
# 你创建了一个函数,这个函数将被用于装饰器。但这个函数也有装饰器装饰
# Don't forget, the signature is "decorator(func, *args, **kwargs)"
# 别忘了,签名是“decorator(func, *args, **kwargs)”
@decorator_with_args 
def decorated_decorator(func, *args, **kwargs): 
    def wrapper(function_arg1, function_arg2):
        print("Decorated with {0} {1}".format(args, kwargs))
        return func(function_arg1, function_arg2)
    return wrapper
# Then you decorate the functions you wish with your brand new decorated decorator.
# 然后你可以用它来装饰你希望装饰的函数
@decorated_decorator(42, 404, 1024)
def decorated_function(function_arg1, function_arg2):
    print("Hello {0} {1}".format(function_arg1, function_arg2))
decorated_function("Universe and", "everything")
#outputs:
#Decorated with (42, 404, 1024) {}
#Hello Universe and everything
# Whoooot!

我知道,上次你有这种感觉,是在听一个人说:“在理解装饰器之前,你必须先理解递归”之后(这里感觉是他写错了,写成了在理解递归之前先要理解递归)。但是现在,你不觉得掌握这个很好吗?

最佳实践:装饰器

  • 装饰器是在 Python 2.4 被引入,所以确保你的代码是运行在 2.4 版本以后
  • 装饰器会降低函数调用的速度。记住这一点。
  • 你不能取消装饰功能。(有一些技巧可以创建可以删除的修饰符,但没有人使用它们。)一旦一个函数被修饰,它就会被所有的代码所修饰。
  • decorator封装了函数,这可能使它们难以调试。(Python >= 2.5更好;见下文)。

functools 模块在 Python 2.5 被引入,它包括函数 functools.wraps(),它会复制被装饰函数的名称、模块和文档说明到包装器中。

(有趣的事实:functools.wraps() 是一个装饰器!)

# For debugging, the stacktrace prints you the function __name__
def foo():
    print("foo")
print(foo.__name__)
#outputs: foo
# With a decorator, it gets messy    
def bar(func):
    def wrapper():
        print("bar")
        return func()
    return wrapper
@bar
def foo():
    print("foo")
print(foo.__name__)
#outputs: wrapper
# "functools" can help for that
import functools
def bar(func):
    # We say that "wrapper", is wrapping "func"
    # and the magic begins
    @functools.wraps(func)
    def wrapper():
        print("bar")
        return func()
    return wrapper
@bar
def foo():
    print("foo")
print(foo.__name__)
#outputs: foo

装饰器怎样才能变得实用(即应用场景)

现在问题来了,我可以用装饰器做什么?

看起来很酷很强大,但是如果有实际例子会更好。这里有1000种可能是它的应用场景。经典的用法是从外部库扩展函数行为(你不能修改它),或者用于调用(你不想修改它,因为它是临时的)

你可以用它们扩展几个功能,比如:

def benchmark(func):
    """
    A decorator that prints the time a function takes
    to execute.
    """
    import time
    def wrapper(*args, **kwargs):
        t = time.clock()
        res = func(*args, **kwargs)
        print("{0} {1}".format(func.__name__, time.clock()-t))
        return res
    return wrapper
def logging(func):
    """
    A decorator that logs the activity of the script.
    (it actually just prints it, but it could be logging!)
    """
    def wrapper(*args, **kwargs):
        res = func(*args, **kwargs)
        print("{0} {1} {2}".format(func.__name__, args, kwargs))
        return res
    return wrapper
def counter(func):
    """
    A decorator that counts and prints the number of times a function has been executed
    """
    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
@logging
def 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

当然,decorator的优点在于,您可以在几乎任何事情上立即使用它们,而无需重写。

@counter
@benchmark
@logging
def get_random_futurama_quote():
    from urllib import urlopen
    result = urlopen("http://subfusion.net/cgi-bin/quote.pl?quote=futurama").read()
    try:
        value = result.split("<br><b><hr><br>")[1].split("<br><br><hr>")[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 使用装饰器来管理缓存和 view 的权限
  • 它是一个内联函数的异步调用
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-06-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 FluentStudy 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、函数是对象
  • 二、函数引用
  • 三、手写装饰器
  • 四、装饰器启发
  • 装饰器进阶
    • 一、向装饰器函数里传入参数
      • 二、装饰方法
        • 四、向装饰器中传入参数
          • 五、练习:装饰一个装饰器
          • 最佳实践:装饰器
          • 装饰器怎样才能变得实用(即应用场景)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档