1. 程式人生 > >python裝飾器(decorator)

python裝飾器(decorator)

import datetime

def calc_spend_time(author):
    def first_deco(func):
        def new_func(*args, **kargs):
            start_time = datetime.datetime.now()
            result = func(*args, **kargs)
            end_tiem = datetime.datetime.now()
            print author, "result:", result, "used:", (end_tiem - start_time).microseconds, "μs"
        return new_func
    return first_deco


@calc_spend_time('author_1')
def calc_add(a, b):
    return a + b


@calc_spend_time('author_2')
def calc_diff(a, b):
    return a - b

calc_add(a=1, b=2)
calc_diff(1, 2)