推荐答案
装饰器(Decorator)是 Python 中一种用于修改或扩展函数或方法行为的语法结构。它允许在不修改原始函数代码的情况下,通过添加额外的功能来“装饰”函数。装饰器本质上是一个函数,它接受一个函数作为参数,并返回一个新的函数。
// www.javascriptcn.com code example
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()输出:
Something is happening before the function is called. Hello! Something is happening after the function is called.
本题详细解读
装饰器的基本概念
装饰器是 Python 中的一种高级功能,它允许你在不修改原始函数代码的情况下,动态地扩展函数的功能。装饰器通常用于日志记录、权限检查、性能测试等场景。
装饰器的语法
装饰器的语法使用 @ 符号,紧跟在装饰器函数名的后面,放在被装饰函数的定义之前。例如:
@decorator
def function():
pass这等价于:
def function():
pass
function = decorator(function)装饰器的工作原理
装饰器的工作原理是通过将原始函数传递给装饰器函数,装饰器函数返回一个新的函数(通常称为 wrapper 或 inner 函数),这个新函数在调用原始函数之前或之后执行额外的代码。
带参数的装饰器
装饰器也可以接受参数,这种情况下需要定义一个返回装饰器的函数。例如:
// www.javascriptcn.com code example
def repeat(num_times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello {name}")
greet("Alice")输出:
Hello Alice Hello Alice Hello Alice
类装饰器
除了函数装饰器,Python 还支持类装饰器。类装饰器通过实现 __call__ 方法来装饰函数。例如:
// www.javascriptcn.com code example
class MyDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("Something is happening before the function is called.")
self.func(*args, **kwargs)
print("Something is happening after the function is called.")
@MyDecorator
def say_hello():
print("Hello!")
say_hello()输出:
Something is happening before the function is called. Hello! Something is happening after the function is called.
总结
装饰器是 Python 中非常强大的工具,它允许你以简洁的方式扩展函数的功能。通过理解装饰器的工作原理和使用场景,你可以编写出更加灵活和可维护的代码。