• Python 装饰器


    Python 装饰器

    1. 简单的装饰器

    下面是一个简单的装饰器示例,它记录被装饰函数的调用信息:

    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    def my_decorator(func):
        def wrapper(x):
            print("Something is happening before the function is called.")
            func(x)
            print("Something is happening after the function is called.")
        return wrapper
    
    @my_decorator
    def say_hello(x):
        print(f"Hello!   {x}")
    
    say_hello('xiao ming ')
    
    # 这样更统一
    def my_decorator(func):
        def wrapper(*args, **kwargs):
            print("Something is happening before the function is called.")
            func(*args, **kwargs)
            print("Something is happening after the function is called.")
        return wrapper
    
    @my_decorator
    def say_hello(x):
        print(f"Hello!   {x}")
    
    say_hello('xiao ming ')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    带参数直接在内层函数添加

    image-20240425205904317

    2. 装饰器带参数

    def repeat(num_times):
        def my_decorator(func):
            def wrapper(x):
                for i in range(num_times):
                    print(f"Something is happening before the function is called.{i}")
                    func(x)
                    print(f"Something is happening after the function is called.{i}", end='\n\n')
            return wrapper
        return my_decorator
    @repeat(3)
    def say_hello(x):
        print(f"Hello!   {x}")
    
    say_hello('xiao ming ')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    image-20240425210254204

    问题:定义一个装饰器,可以计算函数的执行时间

    import time
    def times(num_times):
        def decorated(func):
            def wrapper(x):
                times = 0
                for _ in range(num_times):
                    start = time.time()
                    ret = func(x)
                    times += time.time() - start
                print(f"Average execution time over {num_times} runs: {times:.6f} seconds")
                times /= num_times
                return ret
            return wrapper
        return decorated
    
    @times(5)
    def func(n):
        cnt = 0
        for i in range(1, n+1):
            cnt += i
        return cnt
    func(1000000)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    image-20240425211038981

    3. 类调用

    class CountCalls:
        def __init__(self, func):
            self.func = func
            self.num_calls = 0
    
        def __call__(self, *args, **kwargs):
            self.num_calls += 1
            print(f"Call {self.num_calls} of {self.func.__name__}")
            return self.func(*args, **kwargs)
    
    @CountCalls
    def say_hello():
        print("Hello!")
    say_hello()
    say_hello()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
      return self.func(*args, **kwargs)
    
    • 1

    @CountCalls
    def say_hello():
    print(“Hello!”)
    say_hello()
    say_hello()

    
    ![image-20240425211803257](https://img-blog.csdnimg.cn/img_convert/481ee58543025ee56ecb85999ee96094.png)
    
    • 1
    • 2
  • 相关阅读:
    代码随想录训练营 dp
    基于PHP+mysql的自动化办公OA系统 python+django
    操作系统入门 -- CPU调度算法
    聊聊 Java 数据结构与算法中的堆最小堆和最大堆
    从技术角度看城市停车难问题
    django 任务管理-apscheduler
    读取pdf、docx、doc、ppt、pptx并转为txt
    Mac打开应用提示已损坏怎么办
    Java:实现快速傅里叶变换算法(附完整源码)
    YOLOV7详细解读(四)训练自己的数据集
  • 原文地址:https://blog.csdn.net/qj134206/article/details/138200012