[Python] Simple Decorators

2021-01-02 13:29

阅读:647

标签:eps   bsp   decorator   col   with   simple   round   UNC   span   

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

标签:eps   bsp   decorator   col   with   simple   round   UNC   span   

原文地址:https://www.cnblogs.com/Answer1215/p/12994456.html


评论


亲,登录后才可以留言!