称`super`为`super`

时间:2017-05-31 08:53:13

标签: python python-3.x

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

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声明此处还会调用library_function()中的LibraryCustomHandler.format(),这是我不想要的。

现在,我的工作解决方案是:

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

我想知道是否有更多的pythonic或正确的方式来调用超级超级基本。

1 个答案:

答案 0 :(得分:3)

在这种情况下,调用RotatingFileHandler方法就可以了。你有一个直接的继承模型,不必担心使用 next LibraryCustomHandler可能的mixins。

也就是说,您可以使用LibraryCustomHandler轻松“跳过”super()方法,只需给super()一个不同的起点

super()的第一个参数用于设置在MRO中搜索的起点;通常你将它设置为当前类,并在此点之后开始搜索;对于MyCustomHandler,MRO中的下一个类是LibraryCustomHandler,因此首先会在类中搜索format属性 。但您可以自由地将第一个参数设置为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)

执行此操作时,您还会删除format()MyCustomHandler之间可能位于MRO上的所有LibraryCustomHandler实施。