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 wrapperdef say_hello():print("Hello!")say_hello()outSomething is happening before the function is calledHello!Something is happening after the function is called
多看几遍以上的代码,还有下面的输出结果。假如没有@my_decorator语法糖(syntactic sugar,是指一些简洁和方便的语法结构,它们使代码更易读和编写,但并不会添加新的功能或改变语言的基本行为。),结果是这样:
Hello!
@my_decoratordef say_hello():...
def say_hello():...say_hello = my_decorator(say_hello)
上面划线部分需要复习之前函数部分,*args是代表可变的位置参数,**kwargs是带边可变的关键词参数
def my_decorator(func):def wrapper(*args, **kwargs):print("Before function call")result = func(*args, **kwargs)print("After function call")return resultreturn wrapperdef greet(name):print(f"Hello,{name}!")greet("Alice")outBefore function callHello,Alice!After function call
def my_decorator(func):def wrapper(*args, **kwargs):print("Before function call")result = func(*args, **kwargs)print("After function call")return resultreturn wrapperdef add(a, b):return a + bresult = add(3, 4)print(f"Result: {result}")outBefore function callAfter function callResult:11
def decorator1(func):def wrapper(*args, **kwargs):print("Decorator 1 before")result = func(*args, **kwargs)print("Decorator 1 after")return resultreturn wrapperdef decorator2(func):def wrapper(*args, **kwargs):print("Decorator 2 before")result = func(*args, **kwargs)print("Decorator 2 after")return resultreturn wrapperdef say_hello():print("Hello!")say_hello()outDecorator 1 beforeDecorator 2 beforeHello!Decorator 2 afterDecorator 1 after
def repeat(num_times):def decorator(func):def wrapper(*args, **kwargs):for _ in range(num_times):result = func(*args, **kwargs)return resultreturn wrapperreturn decoratordef say_hello():print("Hello!")say_hello()outHello!Hello!Hello!
functools.wraps 装饰包装函数,保留原函数的元数据。import functoolsdef my_decorator(func):def wrapper(*args, **kwargs):print("Before function call")result = func(*args, **kwargs)print("After function call")return resultreturn wrapperdef say_hello():"""This is a docstring for say_hello function."""print("Hello!")print(say_hello.__name__) # 输出:say_helloprint(say_hello.__doc__) # 输出:This is a docstring for say_hello function.
代码地带
一个简单的缓存装饰器,用于缓存函数的计算结果,避免重复计算。
import functoolsdef cache(func):cached_results = {}def wrapper(*args):if args in cached_results:return cached_results[args]result = func(*args)cached_results[args] = resultreturn resultreturn wrapperdef compute_square(n):return n * nprint(compute_square(4)) # 输出:16print(compute_square(4)) # 输出:16(使用缓存结果)
原创文章,作者:guozi,如若转载,请注明出处:https://www.sudun.com/ask/89543.html