Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 称“super”为“super”`_Python_Python 3.x - Fatal编程技术网

Python 称“super”为“super”`

Python 称“super”为“super”`,python,python-3.x,Python,Python 3.x,我安装了一个具有以下格式的自定义日志处理程序的库: class LibraryCustomHandler(logging.handlers.RotatingFileHandler): # Other LibraryCustomHandler methods def format(self, record): message = super(LibraryCustomHandler, self).format(record) return libr

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

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\u function()
是函数,而不是
LibraryCustomHandler
的方法

我想要一个不同的
库函数()。因此,在这种情况下,我通常会创建一个我想要更改的类的子类:

class MyCustomHandler(path.to.LibraryCustomHandler):
    def format(self, record):
        message = super(MyCustomHandler, self).format(record)
        return my_function(record, message)
但是这里的
super
语句还将从
LibraryCustomHandler.format()
调用
library\u函数()

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

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

我想知道是否有一种更具python风格或正确的方法来调用super-of-super-basicy。

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

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

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)

当你这样做的时候,你也会删掉任何可能位于MRO上的
MyCustomHandler
LibraryCustomHandler

@moooeeep之间的
format()
实现。我想答案就是我给出的“我的工作解决方案”在我的回答中,你可以从中得出结论:你现在的解决方案是可以的,你应该有充分的理由引入一个改变。特别是如果它是一个更不直观,但在这种情况下等效的方法。您是想调用基类的基类方法还是想调用这个特定类提供的方法更相关?如果层次结构发生变化怎么办?在重新阅读您的问题后,我认为这应该是真正的问题:在这种情况下,子类化是取代
library\u function()
行为的正确方法,还是有更好的方法?谢谢您的评论@moooeeep。正如你所说,我没有清楚地阐述我的问题。我的问题实际上是如何“调用基类的基类方法”。我认为描述我的场景模糊了实际的问题,一个更简单地与问题相关的代码示例会更合适。谢谢@martijn pieters,这看起来是正确的做法。请确保包含一个明确的代码注释来解释这一点,否则它很容易看起来像复制/粘贴错误,可能会出错“更正”。好点子@戳