在 python 中的自定义错误 类 中调用 super 有什么意义?

What is the point of calling super in custom error classes in python?

所以我在 Python 中有一个简单的自定义错误 class 是我根据 Python 2.7 文档创建的:

class InvalidTeamError(Exception):
    def __init__(self, message='This user belongs to a different team'):
        self.message = message

这在 PyLint 中给了我警告 W0231: __init__ method from base class %r is not called 所以我去查找它并得到了非常有用的描述 "explanation needed." 我通常会忽略这个错误但我注意到很多在线代码在自定义错误 init 方法的开头包含对 super 的调用 classes 所以我的问题是:这样做真的有目的还是只是人试图安抚虚假的 pylint 警告?

查看 cpython2.7 源代码,避免调用 super init 应该没有问题,是的,这样做只是因为通常调用 base class 在你的初始化中初始化。

https://github.com/python/cpython/blob/master/Objects/exceptions.c 参见第 60 行的 BaseException init 和第 456 行 Exception 如何派生自 BaseException。

这是一个有效的 pylint 警告:如果不使用 superclass __init__,您可能会错过父 class 中的实现更改。而且,事实上,你有 - 因为 BaseException.message 已被弃用 Python 2.6.

这是一个可以避免警告 W0231 的实现,也可以避免 python 关于 message 属性的弃用警告。

class InvalidTeamError(Exception):
    def __init__(self, message='This user belongs to a different team'):
        super(InvalidTeamError, self).__init__(message)

这是一个更好的方法,因为 implementation for BaseException.__str__ 只考虑 'args' 元组,它根本不考虑消息。使用您的旧实现,print InvalidTeamError() 只会打印一个空字符串,这可能不是您想要的!