调用“super”的“super”`

2024-09-24 02:21:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我安装了一个库,该库具有以下格式的自定义日志处理程序:

class LibraryCustomHandler(logging.handlers.RotatingFileHandler):
    # Other LibraryCustomHandler methods

    def format(self, record):
        message = super(LibraryCustomHandler, self).format(record)
        return library_function(record, message)

    # Other LibraryCustomHandler methods

注:library_function()是一个函数,而不是LibraryCustomHandler的方法。

我想要一个不同的library_function()。所以,在这种情况下,我通常会创建一个我想要更改的类的子类:

class MyCustomHandler(path.to.LibraryCustomHandler):
    def format(self, record):
        message = super(MyCustomHandler, self).format(record)
        return my_function(record, message)

但是这里的super语句也将从LibraryCustomHandler.format()调用library_function(),这是我不想要的。你知道吗

现在,我的工作方案是:

class MyCustomHandler(path.to.LibraryCustomHandler):
    def format(self, record):
        message = logging.handlers.RotatingFileHandler.format(self, record)
        return my_function(record, message)

我想知道是否有一个更为python或正确的方式来称呼超级的超级基本上。你知道吗


Tags: selfformatmessagereturnlogginghandlersdeflibrary
1条回答
网友
1楼 · 发布于 2024-09-24 02:21:45

在本例中,调用RotatingFileHandler方法就可以了。您有一个直接的继承模型,不必担心下一步到LibraryCustomHandler可能使用的mixin。他说

这就是说,您也可以通过给super()一个不同的起点来跳过LibraryCustomHandler方法。他说

在这个类中,第一个参数是用来搜索当前值的,所以在这个类中,第一个参数是用来搜索当前值的。但是您可以将第一个参数设置为LibraryCustomHandler

class MyCustomHandler(path.to.LibraryCustomHandler):
    def format(self, record):
        # Explicitly skip LibraryCustomHandler
        message = super(path.to.LibraryCustomHandler, self).format(record)
        return my_function(record, message)

当您这样做的时候,您还可以删掉任何可能位于MyCustomHandlerLibraryCustomHandler之间的MRO上的format()实现。他说

相关问题 更多 >