【问题标题】:How is base Exception getting initialized?如何初始化基本异常?
【发布时间】:2016-10-17 16:35:39
【问题描述】:

我对 Python 3 中的以下异常如何初始化感到困惑。

class MyException( Exception ):

    def __init__(self,msg,foo):
        self.foo = foo

raise MyException('this is msg',123)

在 Python 3 中,此输出:

Traceback (most recent call last):
  File "exceptionTest.py", line 7, in <module>
    raise MyException('this is msg',123)
__main__.MyException: ('this is msg', 123)

如何初始化参数?我很惊讶引用显示了 args,因为我没有调用超类初始化程序。

在 Python 2 中,我得到以下输出,这对我来说更有意义,因为 args 不包含在回溯中。

Traceback (most recent call last):
  File "exceptionTest.py", line 7, in <module>
    raise MyException('this is msg',123)
__main__.MyException

【问题讨论】:

    标签: python python-3.x exception python-2.x


    【解决方案1】:

    Python BaseException 类的特殊之处在于它有一个 __new__ 方法,专门用于处理这种常见的错误情况。

    所以不,BaseException.__init__ 没有被调用,但BaseException.__new__ 。可以覆盖__new__,忽略传入的参数来抑制self.args的设置:

    >>> class MyException(Exception):
    ...     def __new__(cls, *args, **kw):
    ...         return super().__new__(cls)  # ignoring arguments
    ...     def __init__(self,msg,foo):
    ...         self.foo = foo
    ...
    >>> MyException('this is msg', 123)  # no need to raise to see the result
    MyException()
    

    此添加是 Python 3 特有的,在 Python 2 中不存在。有关动机和详细信息,请参阅 issue #1692335

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2012-09-07
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多