Python装饰器函数:让代码更加优雅和可重用
装饰器是Python中的一个非常重要的概念。它可以让我们更加优雅和可重用地编写代码。装饰器是一个函数,它可以将另一个函数作为参数,然后在不改变原函数源代码的情况下,对这个函数进行扩展或者修改。
在Python中,装饰器可以用来实现很多功能,比如:
1. 记录函数运行时间:
import time
def time_it(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start} seconds to run.")
return result
return wrapper
@time_it
def calculate(n):
return sum(range(n))
calculate(10000000)
在上面的例子中,我定义了一个装饰器 time_it,它可以用来记录函数运行的时间。当我们在 calculate 函数上使用 @time_it 装饰器时,calculate 函数将被 time_it 装饰器所包装。time_it 函数相当于一个“中间件”,在调用 calculate 函数之前和之后,它可以执行一些操作。这里,time_it 函数会记录下函数运行前的时间点,函数运行结束后的时间点,然后计算时间差并打印出来。
2. 实现权限控制:
def requires_admin(func):
def wrapper(*args, **kwargs):
if user_is_admin():
return func(*args, **kwargs)
else:
return "Access Denied"
return wrapper
@requires_admin
def do_something():
# do something only admin can do
pass
在上面的例子中,我定义了一个装饰器 requires_admin,它可以用来实现权限控制。当我们在 do_something 函数上使用 @requires_admin 装饰器时,do_something 函数将被 requires_admin 装饰器所包装。requires_admin 函数相当于一个“中间件”,在调用 do_something 函数之前和之后,它可以执行一些操作。这里,requires_admin 函数会检查当前用户是否具有管理员权限,如果是,就执行 do_something 函数,否则返回 “Access Denied”。
3. 缓存函数返回值:
def cache_result(func):
cache = {}
def wrapper(*args):
if args in cache:
print(f"Returning cached result for {args}")
return cache[args]
else:
print(f"Caching result for {args}")
result = func(*args)
cache[args] = result
return result
return wrapper
@cache_result
def fibonacci(n):
if n in (0, 1):
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))
print(fibonacci(10))
在上面的例子中,我定义了一个装饰器 cache_result,它可以用来缓存函数返回值。当我们在 fibonacci 函数上使用 @cache_result 装饰器时,fibonacci 函数将被 cache_result 装饰器所包装。cache_result 函数相当于一个“中间件”,在调用 fibonacci 函数之前和之后,它可以执行一些操作。这里,cache_result 函数会检查当前函数是否已经缓存过,如果是,就返回缓存的结果,否则执行 fibonacci 函数,并将结果缓存起来。
通过上述示例,我们可以清晰地看到,装饰器为我们带来了很多便捷和优雅的写法。装饰器使我们可以将开发精力更多地花在业务逻辑的设计上,而不是浪费在重复性的代码上。通过装饰器,我们可以让代码更加简洁、可读和可重用。当需要修改某个函数的行为时,我们甚至不需要改动原函数的代码,只需要写一个装饰器即可。因此,装饰器是Python编程中的一项非常重要的技术。
