推荐答案
// www.javascriptcn.com code example
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Alice")本题详细解读
装饰器的基本概念
装饰器是 Python 中一种强大的工具,它允许你在不修改原始函数或类定义的情况下,动态地修改它们的行为。装饰器本质上是一个函数,它接受一个函数作为参数,并返回一个新的函数。
装饰器的实现
在上面的示例中,my_decorator 是一个装饰器函数。它接受一个函数 func 作为参数,并返回一个新的函数 wrapper。wrapper 函数在调用原始函数 func 之前和之后执行一些额外的操作。
使用装饰器
通过在函数定义前使用 @my_decorator 语法,我们将 say_hello 函数传递给 my_decorator 装饰器。这样,每次调用 say_hello 时,实际上调用的是 wrapper 函数,从而实现了对 say_hello 行为的修改。
装饰器的应用场景
装饰器常用于以下场景:
- 日志记录
- 权限验证
- 性能测试
- 缓存
- 事务处理
类装饰器
除了函数装饰器,Python 还支持类装饰器。类装饰器的实现方式与函数装饰器类似,只不过它接受一个类作为参数,并返回一个新的类或修改后的类。
// www.javascriptcn.com code example
def my_class_decorator(cls):
class Wrapper:
def __init__(self, *args, **kwargs):
self.wrapped = cls(*args, **kwargs)
def __getattr__(self, name):
return getattr(self.wrapped, name)
return Wrapper
@my_class_decorator
class MyClass:
def __init__(self, value):
self.value = value
def display(self):
print(f"Value: {self.value}")
obj = MyClass(10)
obj.display()在这个例子中,my_class_decorator 是一个类装饰器,它接受一个类 cls 作为参数,并返回一个新的类 Wrapper。Wrapper 类包装了原始类 MyClass,并在调用 MyClass 的方法时执行一些额外的操作。