import logging
import time
from functools import wraps
def calc_time(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
r = func(*args, **kwargs)
time.sleep(2)
end = time.time()
print('普通装饰器 :{}.{} : {}'.format(func.__module__, func.__name__, end - start))
return r
return wrapper
class Calc_time(object):
# def __init__(self, fun):
# self.fun = fun
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
r = func(*args, **kwargs)
time.sleep(1)
end = time.time()
print('类__call__方法:{}.{} : {}'.format(func.__module__, func.__name__, end - start))
return r
return wrapper
@calc_time
def Calc():
return {i for i in range(10) if i >5}
print(Calc())
@Calc_time()
def Add():
return [i+i for i in range(10)]
print(Add())
普通装饰器 :main.Calc : 2.0008223056793213
{8, 9, 6, 7}
类__call__方法:main.Add : 1.0000660419464111
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]