将带有参数的Decorator添加到类的静态方法

时间:2019-12-05 19:01:00

标签: python decorator static-methods

我有一个记录器类,在调用每个记录功能之前,我需要检查记录器是否已配置。如果是,则__logger_configured类变量将为true。鉴于每次调用静态方法时都需要检查此方法,因此我想对所有静态方法进行包装,并检查此成员变量。

这很棘手,因为:

  1. 我想将参数传递给装饰器
  2. 我希望该参数引用该实例,但是在装饰时该实例不存在,所以我不得不以某种方式推迟它。

我该怎么做?

class Logger:

     __logger_configured = False

     # Other stuff...

     # Logger now configured. Other static member functions are unlocked.
     Logger.__logger_configured = True


    ###########################
    ####### Decorators ########
    ###########################

    # We don't want checkLoggerStatus to be a member function of Logger. Hence
    # Hence, make it a staticmethod of a private nested class.

    class _Decorators:

        @staticmethod
        def check_logger_status(func, logger_status: bool):

            def wrapper(*args, **kwargs):
                if not logger_status:
                    raise ValueError('[ERROR] -- The Logger has not yet been configured. '
                                     'Please first configure the logger '
                                     'via its config_logger staticmethod')
                else:
                    func(*args, **kwargs)

            return wrapper

    ##########################
    ### Logging Facilities ###
    ##########################

     # Other stuff...

    @staticmethod
    @_Decorators.check_logger_status(__logger_configured)
    def log_info(operation: str):
        Logger.update_time()

        # Write to file
        with open(Logger.__filename, Logger.__filemode) as ourFile:
            ourFile.write('[INFO] {} -- {}'.format(Logger.__last_update, operation))


    # Other stuff...

0 个答案:

没有答案