装饰器

# -*- coding:utf-8

def a_new_decorator(a_func):
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")
    return wrapTheFunction

@a_new_decorator
def a_function_requiring_decoration():
    """Hey you! Decorate me!"""
    print("I am the function which needs some decoration to " "remove my foul smell")

a_function_requiring_decoration()
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

输出结果

 装饰器的常用场景:

# -*- coding:utf-8
from functools import wraps

def decorator_name(f):
    @wraps(f)
    def decorated(*args,**kwargs):
        if not can_run:
            return "Function will not run!"
        return f(*args,**kwargs)
    return decorated

@decorator_name
def func():
    return ("Function is running!")

can_run = True
print (func())

 

posted @ 2020-03-27 15:29  南山散人  阅读(80)  评论(0编辑  收藏  举报