python装饰器示例

不带参数:

import datetime
import time


def duration(f):
    def wraper(*args, **kwargs):
        start = datetime.datetime.now()
        ret = f(*args, **kwargs)
        end = datetime.datetime.now()
        print("function {} took {}s".format(f.__name__, (end - start).total_seconds()))
        return ret
    return wraper


@duration
def add(x, y):
    print("call add function.")
    time.sleep(1)
    return x + y

print(add(4, 5))

 

 

带参数:

import datetime
import time


def duration(t):
    def _duration(f):
        def wraper(*args, **kwargs):
            start = datetime.datetime.now()
            ret = f(*args, **kwargs)
            end = datetime.datetime.now()
            if (end - start).total_seconds() > t:
                print("function {} took {}s".format(f.__name__, (end - start).total_seconds()))
            return ret
        return wraper
    return _duration


@duration(2)
def add(x, y):
    print("call add function.")
    time.sleep(1)
    return x + y

print(add(4, 5))

 

posted @ 2021-09-18 16:39  kunsile  阅读(38)  评论(0编辑  收藏  举报