【问题标题】:What is the point of calling super in custom error classes in python?在 python 的自定义错误类中调用 super 有什么意义?
【发布时间】:2023-03-17 04:22:01
【问题描述】:

所以我在 Python 中有一个基于 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,所以我去查找它并得到“需要解释”的非常有用的描述。我通常会忽略这个错误,但我注意到在线的大量代码在自定义错误类的 init 方法的开头包含对 super 的调用,所以我的问题是:这样做真的有用吗目的还是只是人们试图安抚虚假的 pylint 警告?

【问题讨论】:

    标签: python python-2.7 exception pylint


    【解决方案1】:

    这是一个有效的 pylint 警告:如果不使用超类 __init__,您可能会错过父类中的实现更改。而且,确实,你有 - 因为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() 只会打印一个空字符串,这可能不是您想要的!

    【讨论】:

    • 为链接到 C 实现点赞。马上就明白了,怎么回事!
    • 恼人的是the Python docs 实际上建议使用self.message 方法而不是调用super() 方法。
    • @kevlarr 嗯,是的,那部分文档已有 10 多年的历史,并且可能早于 BaseException.message 的弃用。
    • 绝对 - 文档 for 3.8 并没有真正保持最新,这有点误导,但我理解为什么它们不是......表面积令人惊讶大。
    【解决方案2】:

    查看 cpython2.7 源代码,避免调用 super init 应该没有问题,是的,这样做只是因为在你的 init 中调用基类 init 通常是一个好习惯。

    https://github.com/python/cpython/blob/master/Objects/exceptions.c 请参阅第 60 行了解 BaseException init 和第 456 行 Exception 如何从 BaseException 派生。

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2011-04-13
      • 1970-01-01
      • 2019-06-07
      • 2016-02-26
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多