代码b中超级引用接口的含义

2024-09-30 04:35:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

为什么我们需要在超级传递信息。该消息是否为GenericMaxException从say Exception类继承的类中的任何函数的参数?我知道super正在引用基类属性。。但是无法理解为什么在super内部调用message参数


Tags: selflayermessageforbase参数initdef
1条回答
网友
1楼 · 发布于 2024-09-30 04:35:06

默认情况下,如果在引发异常时使用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.

相关问题 更多 >

    热门问题