我安装了一个具有自定义日志处理程序的库,格式如下:
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或正确的方式来调用超级超级基本。
答案 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
实施。