Python装饰器的定义、应用和实例
发布时间:2023-06-23 21:18:28
Python装饰器是一个函数,它可以在不改变原函数代码的情况下,动态地修改函数的行为和功能。使用装饰器,我们可以实现一些常见的代码重用和增强功能的方式。
装饰器的应用主要包括以下几个方面:
1. 计时器
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f'Time used: {end - start:.5f}s')
return result
return wrapper
@timer
def func():
time.sleep(1)
func() # 显示:Time used: 1.00021s
2. 登录认证
def login_required(func):
def wrapper(*args, **kwargs):
if not is_logged_in():
login()
return func(*args, **kwargs)
return wrapper
@login_required
def admin_page():
print('Welcome to the admin page!')
3. 日志记录
def log(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
with open('log.txt', 'a') as f:
f.write(f'{func.__name__} was called at {time.ctime()}
')
return result
return wrapper
@log
def say_hello():
print('Hello world!')
say_hello()
以上只是装饰器的几个基础应用,实际上,装饰器还可以实现很多高级功能,例如缓存结果、异常处理、接口调用等。下面是一个更加复杂的实例:
import time
cache = {}
def memoize(func):
def wrapper(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache.keys():
result = None
try:
result = func(*args, **kwargs)
except Exception as e:
print(f'Error occurred: {e}')
cache[key] = result
return cache[key]
return wrapper
@memoize
def slow_api_call(param1, param2):
time.sleep(1)
return 'result'
print(slow_api_call(1, 2)) # 1s delay, prints "result"
print(slow_api_call(1, 2)) # prints "result" without delay, using cache
print(slow_api_call(2, 3)) # 1s delay, prints "result"
这个例子演示了如何使用装饰器实现结果缓存,避免重复计算。使用装饰器的好处是,不需要修改原代码,只需要添加一个装饰器即可。
总之,Python装饰器是一个非常有用的功能,可以帮助我们简化代码、增强功能、提高性能、方便测试和调试等。学习和掌握装饰器的使用,对程序员的能力和技能水平都有很大的提升作用。
