Python装饰器

# encoding=utf-8

import time


# def comsume(f):
#     def wrapper(*args, **kwargs):
#         t1 = time.time()
#         result = f(*args, **kwargs)
#         t2 = time.time()
#         print t2-t1
#         return result
#     return wrapper
#
#
# @comsume
# def sum(start, end):
#     result = start
#     for i in range(start, end):
#         result += i
#     return result

# 带参数的装饰器
def consume(times):
    def func(f):
        print 'run with para times=%s'%times

        def wrapper(*args, **kwargs):
            t1 = time.time()
            result = f(*args, **kwargs)
            t2 = time.time()
            print t2-t1
            return result
        return wrapper
    return func


@consume(times=3)
def sum(start, end):
    result = start
    for i in range(start, end):
        result += i
    return result


if __name__ == '__main__':
    print sum(1, 10000)
    # consume(times)(ff)(1, 1000)

import time


def consume(f):
    def wrapper(*args, **kwargs):
        t1 = time.time()
        s = f(*args, **kwargs)
        t2 = time.time()
        print 'time', t2 - t1
        return s

    return wrapper
    # consume(fff)=wrapper


def fff(x, y):
    return x + y

print consume(fff)(1, 2)

你可能感兴趣的:(Python装饰器)