【问题标题】:Declaring decorator method inside of a mixin class在 mixin 类中声明装饰器方法
【发布时间】:2021-01-04 23:06:19
【问题描述】:

我写了一个这样的类:

class AbstractBigHandler(AbstractHandler, ActionTimer):
    def __init__(self, path, data_container):
        
        AbstractHandler.__init__(self)
        ActionTimer.__init__(self, data_container)

    @time_action
    def handle(self, request):
        # Do something

我想给其中的handle()方法计时,所以我想出了一个想法来编写一个mixin类,它会在其中提供一个装饰器类,因为在我看来,它可以很好地分离关注点代码。此外,我希望这个 mixin 类可以被我稍后编写的其他类重用:

class ActionTimer:

    def __init__(self, data_container):
        self.data_container = data_container
        self.class_name = self.__class__.__name__

    def time_action(self, func):
        def wrapper(self, func, *args, **kwargs):
            start_time = datetime.now()
            func_output = func.handle(args, kwargs)
            end_time = datetime.now()

            execution_time = end_time - start_time
            print(self.__class__.__name__, " execution time: ", execution_time)

            self.data_container.add_data(self.class_name, execution_time)

            return func_output

        return wrapper

其中的 data_container 参数只是一个我打算浮动的单例,并在其字典属性中收集数据(通过 .add_data() 方法)。

现在,当我尝试为 AbstractBigHandler 类运行测试时,它在实例化时立即失败,并出现以下错误堆栈:

C:\project\tests>python -m unittest test_abstract_big_handler
Traceback (most recent call last):
  File "C:\Users\***\AppData\Local\Continuum\anaconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\***\AppData\Local\Continuum\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\***\AppData\Local\Continuum\anaconda3\lib\unittest\__main__.py", line 18, in <module>
    main(module=None)
  File "C:\Users\***\AppData\Local\Continuum\anaconda3\lib\unittest\main.py", line 100, in __init__
    self.parseArgs(argv)
  File "C:\Users\***\AppData\Local\Continuum\anaconda3\lib\unittest\main.py", line 147, in parseArgs
    self.createTests()
  File "C:\Users\***\AppData\Local\Continuum\anaconda3\lib\unittest\main.py", line 159, in createTests
    self.module)
  File "C:\Users\***\AppData\Local\Continuum\anaconda3\lib\unittest\loader.py", line 220, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "C:\Users\***\AppData\Local\Continuum\anaconda3\lib\unittest\loader.py", line 220, in <listcomp>
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "C:\Users\***\AppData\Local\Continuum\anaconda3\lib\unittest\loader.py", line 154, in loadTestsFromName
    module = __import__(module_name)
  File "C:\project\tests\test_abstract_big_handler.py", line 5, in <module>
    from project.common.handlers.AbstractBigHandler import AbstractBigHandler
  File "C:\project\common\handlers\AbstractBigHandler.py", line 17, in <module>
    class AbstractBigHandler(AbstractHandler, ActionTimer):
  File "C:\project\common\handlers\AbstractBigHandler.py", line 69, in AbstractBigHandler
    @time_action
NameError: name 'time_action' is not defined

我不确定为什么会发生这种情况 - 因为 ActionTimer 类作为第二个继承类添加到 AbstractBigHandler 类中,它的方法 time_action() 应该(并且当我检查 PDB 时)存在于 AbstractBigHandler 的方法中.

帮助?

【问题讨论】:

    标签: python python-3.x oop decorator


    【解决方案1】:

    因为time_action是装饰器,你不需要在wrapped中再次传递func。由于容器是Singleton,所以可以使用classmethod直接引用。

    from datetime import datetime
    import random
    
    
    class AbstractHandler(object):
        pass
    
    
    class ActionTimer(object):
        data_container = []
    
        def __init__(self, data_container):
            self.data_container = data_container
            self.class_name = self.__class__.__name__
    
        @classmethod
        def time_action(cls, func):
            def wrapper(*args, **kwargs):
                start_time = datetime.now()
                func_output = func(*args, **kwargs)
                end_time = datetime.now()
                execution_time = end_time - start_time
    
                # just some random value to show results (remove)
                execution_time = execution_time.total_seconds() + random.randrange(1, 10, 1)
    
                print(cls.__name__, " execution time: ", execution_time)
    
                cls.data_container.append((cls.__name__, execution_time))
    
                return func_output
    
            return wrapper
    
    
    class AbstractBigHandler(AbstractHandler, ActionTimer):
        def __init__(self, path, data_container):
            AbstractHandler.__init__(self)
            ActionTimer.__init__(self, data_container)
    
        @classmethod
        @ActionTimer.time_action
        def handle(cls, request):
            print(request, "CONTAINER:", cls.data_container)
    
    
    a = AbstractBigHandler("path", [])
    for i in range(5):
        a.handle("some-request-" + str(i))
    print("FINAL:", ActionTimer.data_container)
    
    

    产生以下内容:

    some-request-0 CONTAINER: []
    ActionTimer  execution time:  9.0
    some-request-1 CONTAINER: [('ActionTimer', 9.0)]
    ActionTimer  execution time:  6.0
    some-request-2 CONTAINER: [('ActionTimer', 9.0), ('ActionTimer', 6.0)]
    ActionTimer  execution time:  9.0
    some-request-3 CONTAINER: [('ActionTimer', 9.0), ('ActionTimer', 6.0), ('ActionTimer', 9.0)]
    ActionTimer  execution time:  3.0
    some-request-4 CONTAINER: [('ActionTimer', 9.0), ('ActionTimer', 6.0), ('ActionTimer', 9.0), ('ActionTimer', 3.0)]
    ActionTimer  execution time:  5.0
    FINAL: [('ActionTimer', 9.0), ('ActionTimer', 6.0), ('ActionTimer', 9.0), ('ActionTimer', 3.0), ('ActionTimer', 5.0)]
    
    

    【讨论】:

      【解决方案2】:

      不幸的是,继承的命名空间仅在类主体被完全定义后处理。对于像AbstractBigHandler 这样的子类来说,在类定义时引用其父类的属性并不容易。一个更简单的问题示例是:

      class A:
          foo = 1
      
      class B(A):         # inherit the foo class attribute
          bar = foo + 1   # but looking it up here fails, with the same NameError you're seeing
      

      要解决此问题,您要么需要显式引用父类(例如,B 中的 A.foo),要么将要从父类继承的值改为全局变量。对于需要在定义子类时应用的装饰器,这通常是最好的方法,而不是在将实例作为 self 传递给方法时。

      确实,这是我在您的代码中看到的第二个问题,即您的装饰器有一些混乱的参数(在装饰器本身和内部的包装函数中)。我建议这样的结构:

      class ActionTimer:
          def __init__(self, data_container):
              self.data_container = data_container
              self.class_name = self.__class__.__name__
      
      def time_action(func):                     # top-level function, no self arg here
          def wrapper(self, *args, **kwargs):    # no func arg here, but we *do* have a self arg
              start_time = datetime.now()
              func_output = func(self, args, kwargs)   # don't call handle, *we're* handle!
              end_time = datetime.now()
      
              execution_time = end_time - start_time
              print(self.__class__.__name__, " execution time: ", execution_time)
      
              self.data_container.add_data(self.class_name, execution_time)
      
              return func_output
      
          return wrapper
      

      现在AbstractBigHandler 类将按照您编写的方式工作。

      【讨论】:

        猜你喜欢
        • 2016-11-26
        • 2019-10-02
        • 1970-01-01
        • 1970-01-01
        • 2019-08-07
        • 2014-01-14
        • 2020-01-11
        • 1970-01-01
        • 2023-01-28
        相关资源
        最近更新 更多