最近发现装饰器是一个非常有意思的东西,很高级!

允许你在不修改函数或类的源代码的情况下,为它们添加额外的功能或修改它们的行为。装饰器本质上是一个接受函数作为参数的可调用对象(通常是函数或类),并返回一个新函数。

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 函数时,它实际上会调用 wrapper 函数,  
# wrapper 函数在调用 say_hello 之前和之后都添加了一些额外的输出。  
say_hello("Alice")

本站无任何商业行为
个人在线分享 » python中装饰器的用法
E-->