首页 > 解决方案 > 代码块中超级引用接口的含义

问题描述

class GenericMaxException(Exception):
     """Base class for all Max layer exceptions."""

     def __init__(self, *, message):
         """
         Constructor.

         Parameters:
             Required:
                 message - String describing exception.

             Optional:
                 None
         """

         super().__init__(message)

为什么我们需要在 super. 消息是否是 GenericMaxException 继承自 Exception 类的类中任何函数的参数。? 我知道 super 正在引用基类属性..但无法理解为什么在 super 中调用 message 参数。

标签: pythonpython-3.xoop

解决方案


默认情况下,如果super在引发异常时没有传递任何内容,则没有任何解释,它只在跟踪中显示引发异常的位置/哪一行。但是在引发异常时传递消息会给出解释。

示例 1:

class GenericMaxException(Exception):
    """Base class for all Max layer exceptions."""

    def __init__(self, * ,message):
        """
        Constructor.

        Parameters:
            Required:
                message - String describing exception.

            Optional:
                None
        """

        super().__init__()


raise GenericMaxException(message="This is the reason.")

输出 :

Traceback (most recent call last):
  File "/home/user/PycharmProjects/pythonTutorials/tutorials/temp.py", line 19, in <module>
    raise GenericMaxException(message="This is the reason.")
__main__.GenericMaxException  # No explanation why it occurred only mentioned is where it occurred

示例 2:

class GenericMaxException(Exception):
    """Base class for all Max layer exceptions."""

    def __init__(self, *, message):
        """
        Constructor.

        Parameters:
            Required:
                message - String describing exception.

            Optional:
                None
        """

        super().__init__(message)


raise GenericMaxException(message="This is the reason.")

输出 :

Traceback (most recent call last):
  File "/home/user/PycharmProjects/pythonTutorials/tutorials/temp.py", line 19, in <module>
    raise GenericMaxException(message="This is the reason.")
__main__.GenericMaxException: This is the reason. # Here is the explanation.

推荐阅读