Python中使用装饰器的函数-装饰器使用方法和实例
发布时间:2023-11-04 15:50:55
装饰器是Python中一种非常强大的编程工具,可以用于修改函数的行为或在函数执行前后添加额外的功能。装饰器本质上是一个函数,它接受一个函数作为参数,并返回一个新的函数。
使用装饰器的方法非常简单。首先定义一个装饰器函数,然后在要被装饰的函数前面加上@装饰器函数的名字。下面是一个装饰器的示例:
def decorator_func(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
@decorator_func
def hello():
print("Hello, World!")
hello()
输出结果为:
Before function execution Hello, World! After function execution
在上面的示例中,我们定义了一个装饰器函数decorator_func,它接受一个函数作为参数,并返回一个内部函数wrapper。在wrapper函数中,我们可以在被装饰的函数执行前后添加额外的代码。最后,我们用@decorator_func来标记hello函数,表示将hello函数传递给decorator_func函数进行装饰。
装饰器的使用非常灵活,它可以用来实现很多有用的功能。下面是几个装饰器的示例:
1. 计时器装饰器
import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print("Execution time: {} seconds".format(end_time - start_time))
return result
return wrapper
@timer_decorator
def calculate_sum(n):
total = 0
for i in range(1, n+1):
total += i
return total
print(calculate_sum(1000000))
输出结果为:
Execution time: 0.038275957107543945 seconds 500000500000
在上面的示例中,我们定义了一个计时器装饰器timer_decorator,它可以用来计算被装饰函数的执行时间。在wrapper函数中,我们使用time.time()函数来获取当前时间,并在被装饰函数执行前后计算时间差,并输出执行时间。
2. 权限验证装饰器
def check_permission(permission):
def decorator(func):
def wrapper(*args, **kwargs):
if permission == "admin":
print("Admin permission granted")
return func(*args, **kwargs)
else:
print("Permission denied")
return wrapper
return decorator
@check_permission("admin")
def delete_user(user_id):
print("Deleting user with ID: {}".format(user_id))
delete_user(123)
输出结果为:
Admin permission granted Deleting user with ID: 123
在上面的示例中,我们定义了一个权限验证装饰器check_permission,它接受一个权限参数,并返回一个装饰器函数decorator。在wrapper函数中,我们根据权限参数判断是否有权限执行被装饰函数。
装饰器是Python中非常有用的特性,可以帮助我们在不修改原函数代码的情况下实现额外的功能。通过定义不同的装饰器,我们可以实现很多有用的功能,如计时器、日志记录、权限验证等。掌握装饰器的使用方法,可以帮助我们写出更加灵活和可维护的代码。
