mug*_*ump 7 python pylint super python-2.7
Pylint提出警告:Useless super delegation in method '__init__' (useless-super-delegation)对于SpecificError下面的课程.
class MyProjectExceptions(Exception):
"""The base class for all my project's exceptions."""
def __init__(self, message, func):
super(MyProjectExceptions, self).__init__(message) # Normal exception handling
self.func = func # Error origin for logging
class SpecificError(MyProjectExceptions):
"""Raise when a specific error occurs."""
def __init__(self, message, func):
super(SpecificError, self).__init__(message, func)
Run Code Online (Sandbox Code Playgroud)
在这里将参数传递给超类的正确方法是什么?
正如Mathieu 提到的,您不需要__init__通过调用来覆盖super():
class SpecificError(MyProjectExceptions):
"""Raise when a specific error occurs."""
pass
Run Code Online (Sandbox Code Playgroud)
Pylint 的开发人员useless-super-delegation在Pylint 变更日志上更深入地解释了:
useless-super-delegation[is] 每当我们可以检测到一个被覆盖的方法无用时,就使用它,依靠super()委托来做与 MRO 中的另一个方法相同的事情。例如,在这个例子中,前两个方法是无用的,因为它们与基类中的方法做完全相同的事情,而接下来的两个方法不是,因为它们对传递的参数执行一些额外的操作。
Run Code Online (Sandbox Code Playgroud)class Impl(Base): def __init__(self, param1, param2): super(Impl, self).__init__(param1, param2) def useless(self, first, second): return super(Impl, self).useless(first, second) def not_useless(self, first, **kwargs): debug = kwargs.pop('debug', False) if debug: ... return super(Impl, self).not_useless(first, **kwargs) def not_useless_1(self, first, *args): return super(Impl, self).not_useless_1(first + some_value, *args)
警告的创建者在提交消息中进一步解释:
每当 pylint 可以检测到而不是覆盖的方法无用时,就会使用它,依靠
super()委托来实现与MRO 的另一种方法相同的事情。在这种情况下,不实现给定的方法并让它从 MRO 传播到另一个实现就足够了。
有关原始问题报告,请参阅#839 - Pylint 规则,禁止人们为了调用 super 而覆盖方法。
如果你打电话给SpecificError它,它会寻找一个__init__.如果它不存在,它将调用父项__init__.没有必要在__init__这里添加,因为它与父类完全相同.它基本上是代码重复.
你应该做:
class SpecificError(MyProjectExceptions):
"""Raise when a specific error occurs."""
pass
Run Code Online (Sandbox Code Playgroud)