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参数。
答案 0 :(得分:1)
默认情况下,如果在引发异常时没有使用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.