1、无参函数装饰器
import time
def timeit(f):
def wrapper(*args, **kwargs):
start = time.time()
ret = f(*args, **kwargs)
print(time.time() - start)
return ret
return wrapper
@timeit
def my_func(x):
time.sleep(x)
@timeit
def other_func(x):
return 2 * x
@timeit
def add(x, y):
return x + y
# 等价于
# double = dec(double)
# my_func(1)
# other_func(2)
add(8, 9)
2、有参函数装饰器
import time
def timeit(iteration):
def inner(f):
def wrapper(*args, **kwargs):
start = time.time()
for _ in range(iteration):
ret = f(*args, **kwargs)
print(time.time() - start)
return ret
return wrapper
return inner
@timeit(200000)
def double(x):
return 2 * x
# 等价于
# double = timeit(200000)(double)
double(2)
3、无参装饰器类
import time
class Timer:
def __init__(self, func) -> None:
self.func = func
def __call__(self, *args, **kwds):
start = time.time()
ret = self.func(*args, **kwds)
print(time.time() - start)
return ret
@Timer
def add(x, y):
return x + y
# 等价于
# add = Timer(add)
add(2, 3)
4、有参装饰器类
import time
class Timer:
def __init__(self, prefix) -> None:
self.prefix = prefix
def __call__(self, func):
def wrapper(*args, **kwds):
start = time.time()
ret = func(*args, **kwds)
print(f'{self.prefix}{time.time() - start}')
return ret
return wrapper
@Timer(prefix='run_time: ')
def add(x, y):
return x + y
# 等价于
# add = Timer('run_time: ')(add)
add(2, 3)
5、装饰类的装饰器
def add_str(cls):
def __str__(self):
return str(self.__dict__)
cls.__str__ = __str__
return cls
@add_str
class MyObject:
def __init__(self, a, b) -> None:
self.a = a
self.b = b
# 等价于
# MyObject = add_str(MyObject)
my_object = MyObject(1, 2)
str(my_object)