装饰器是Python中的一种特殊语法,它可以用于修改、扩展或包装函数的功能。简单来说,装饰器是一个函数,它接受一个函数作为输入,并返回一个新的函数作为输出。这个新的函数通常会在原函数的基础上添加一些额外的功能,如打印日志、计时等。
下面是两个Python代码例子,分别展示了装饰器的应用:
日志装饰器:
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
print(next(gen)) # 输出 1
print(next(gen)) # 输出 2
print(next(gen)) # 输出 3
输出结果:
Calling function: say_hello
Hello, Alice
在上面的例子中,我们定义了一个日志装饰器log_decorator
,它接受一个函数作为输入,并返回一个新的函数wrapper
。wrapper
函数会在调用原函数之前打印日志,然后再调用原函数。通过在say_hello
函数上添加@log_decorator
装饰器,我们实际上实现了在调用say_hello
函数时自动打印日志的功能。
计时装饰器:
import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print("Function", func.__name__, "executed in", end_time - start_time, "seconds")
return result
return wrapper
@timer_decorator
def calculate_sum(n):
sum = 0
for i in range(n+1):
sum += i
return sum
print(calculate_sum(1000000))
输出结果:
Function calculate_sum executed in 0.0509028434753418 seconds
500000500000
在上面的例子中,我们定义了一个计时装饰器timer_decorator
,它能够计算被装饰函数的执行时间。通过在calculate_sum
函数上添加@timer_decorator
装饰器,我们实际上实现了在调用calculate_sum
函数时自动计算执行时间的功能。