“Python函数的装饰器的作用与用法”:讲解Python函数装饰器的概念和常用方法。
Python函数装饰器的概念
在 Python 中,装饰器是一种高级特性,它可以动态地改变某个函数的行为。Python中,函数是一等公民,这意味着函数可以作为参数传入其他函数,也可以被其他函数返回。Python中的装饰器利用了函数作为返回值的功能,把一个函数传入另一个函数中进行处理,然后返回一个新的函数。通俗的来说,装饰器是一个函数,它可以用来装饰其他函数,即为其他函数添加一些额外的功能。
Python函数装饰器的常用方法
在 Python 中,函数装饰器使用 @ 符号赋值,它可以放置在函数定义前面,并加上装饰器函数的名称。下面是一个简单的例子:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
在上面的代码中,my_decorator 函数就是一个装饰器。它定义了一个内部函数 wrapper,这个函数就是我们要添加的新功能。这个新功能定义了在原函数执行前和执行后要执行的程序。
装饰器是如何工作的?
当我们通过 @my_decorator 来装饰 say_hello 函数时,实际上相当于这样写:
say_hello = my_decorator(say_hello)
在这个过程中,my_decorator 函数是被执行了一次的。它将原函数作为参数传入了其中,并返回了一个新的函数。这个新的函数就是我们实际上执行的函数。当我们最后调用 say_hello 函数时,实际上调用的是经过装饰器 decorator 处理后的新函数 wrapper。
常用的装饰器示例
下面,我们来看一些实际的装饰器示例。
1. 记录函数执行时间
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Executed {func.__name__} in {end - start} seconds")
return result
return wrapper
@timing_decorator
def slow_function():
time.sleep(2)
slow_function()
2. 校验用户权限
def user_roles(role):
def decorator(func):
def wrapper(*args, **kwargs):
if role == "admin":
return func(*args, **kwargs)
else:
return "You are not authorized to perform this action."
return wrapper
return decorator
@user_roles("admin")
def delete_user(user_id):
print(f"Deleting user {user_id}")
delete_user(123)
在上述代码示例中,定义了一个装饰器函数 user_roles,它有一个参数 role。在 user_roles 中,定义了一个新的函数 decorator,它接受一个func函数作为参数,并返回一个新的函数 wrapper。wrapper 中执行了一些校验逻辑,如果用户的权限符合条件,则执行原函数并返回结果;否则,返回错误提示信息。
3. 缓存函数结果
def memoization_decorator(func):
memo = {}
def wrapper(*args):
if args in memo:
return memo[args]
else:
result = func(*args)
memo[args] = result
return result
return wrapper
@memoization_decorator
def fibonacci(n):
if n < 2:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(40))
这个示例展示了一个实现函数结果缓存的装饰器。在函数执行前,检查参数值是否已经存在于缓存中,如果是,则直接返回缓存中的值,否则执行函数并将结果加入到缓存中再返回。
总结
Python 中的函数装饰器像是在不改变原函数的代码的情况下,增强原函数的功能。装饰器可以在简化代码,增强程序的可读性,提高代码复用性等方面优势。本文主要讲解了 Python 中函数装饰器的概念和常用方法,通过代码实现,希望读者能够加深对 Python 函数装饰器的理解。
