Python的函数装饰器如何工作?
发布时间:2023-06-20 08:25:25
Python的函数装饰器是一种以函数为输入并输出一个被修改函数的函数。在Python中,函数本身也是一种对象,因此可以被传递和返回。装饰器是一种可以动态修改函数行为、添加新功能、或执行某些操作的工具。Python中常用的装饰器有@classmethod、@staticmethod、@property、@asyncio等。
装饰器本质上是一个闭包函数,它将被装饰的函数作为输入参数,通过添加新的代码、修改或增强原函数的功能,返回一个新的、被修改后的函数对象。
下面是一个示例:
def my_decorator(func):
def wrapper():
print("Before function is called.")
func()
print("After function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
在这个例子中,我们定义了一个装饰器函数my_decorator,它接受一个函数作为输入参数func,并返回一个新的函数wrapper,该函数内部在调用原函数前后添加了一些操作。然后使用@my_decorator语法将say_hello函数进行装饰,使其调用时会先输出“Before function is called.”,然后执行原函数,最后输出“After function is called.”。
装饰器的作用可以有很多种,例如:
1. 记录函数执行时间:
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print("Time elapsed: {:.2f}s".format(end_time - start_time))
return result
return wrapper
@timer
def my_func():
time.sleep(2)
print("Function is called")
my_func()
2. 检查用户登录状态:
def login_required(func):
def wrapper(user):
if user.is_authenticated():
return func(user)
else:
raise Exception("User is not authenticated")
return wrapper
@login_required
def my_func(user):
print("Hello, "+ user.name)
my_func(my_user)
3. 实现缓存:
def cache(func):
cached_data = {}
def wrapper(*args):
if args in cached_data:
return cached_data[args]
else:
result = func(*args)
cached_data[args] = result
return result
return wrapper
@cache
def my_func(x, y):
print("Computing...")
return x + y
my_func(1, 2)
my_func(1, 2)
在这个例子中,我们定义了一个装饰器函数cache,它内部维护了一个字典cached_data,用于缓存被装饰函数的输入和输出。在调用被装饰函数时,如果输入参数已经在缓存中存在,则立刻返回缓存中的结果;否则执行原函数,并将结果添加到缓存中。
总的来说,Python的函数装饰器是一种非常实用、灵活和强大的工具,可以在不修改原函数代码的情况下,轻松添加新功能、优化性能、或进行其它操作。熟练掌握函数装饰器的使用方法,对于提高代码的可读性、可维护性、可扩展性等方面都有很大的帮助,值得开发者深入学习和掌握。
