[Python] Simple Decorators

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Python] Simple Decorators相关的知识,希望对你有一定的参考价值。

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

def say_whee():
    print("Whee!")

say_whee = my_decorator(say_whee)
>>> say_whee()
Something is happening before the function is called.
Whee!
Something is happening after the function is called.

 Instead, Python allows you to use decorators in a simpler way with the @ symbol, sometimes called the “pie” syntax. The following example does the exact same thing as the first decorator example:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_whee():
    print("Whee!")

 

More: https://realpython.com/primer-on-python-decorators/

以上是关于[Python] Simple Decorators的主要内容,如果未能解决你的问题,请参考以下文章

python 来自http://code.activestate.com/recipes/577479-simple-caching-decorator/

python [Python Async Decorator] #python #asyncio #decorator

Python Decorator

Python中的@property和decorator

python中完善decorator

python中的decorator模块