不带参数装饰器(两层)
import time
def decorator(func):
def wrapper(*args, **kwargs):
print(f'{func.__name__} is running.')
result = func(*args, **kwargs)
return result
return wrapper
def decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f'{func.__name__} execution time:{end_time-start_time} seconds.')
return result
return wrapper
decorated_square = decorator(square)
decorated_square(10)
square = decorator(square)
square(10)
@decorator
def square(x):
return x * x
square(10)
带参数的装饰器
import time
def transfer_parameters(param):
def decorator(func):
def wrapper(*args, **kwargs)
result = func(*args, **kwargs)
return result
return wrapper
return decorator
def timer(threshold):
def decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
if end_time - start_time > threshold:
print(f'{func__name__} took longer than {threshold} seconds.')
return result
return wrapper
return decorator
@timer(0.2)
def sleeped():
time.sleep(0.4)
sleeped()
sleep = timer(0.2)(sleeped)
sleeped.__name__
```python
import functools
import time
def transfer_parameters(param):
def decorator(func):
def wrapper(*args, **kwargs)
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@timer(0.2)
def sleeped():
time.sleep(0.4)
sleeped()
sleeped.__name__