码迷,mamicode.com
首页 > 编程语言 > 详细

[Python] Simple Decorators

时间:2020-05-30 20:15:38      阅读:77      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!