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)
为什么我们需要在 super. 消息是否是 GenericMaxException 继承自 Exception 类的类中任何函数的参数。? 我知道 super 正在引用基类属性..但无法理解为什么在 super 中调用 message 参数。
解决方案
默认情况下,如果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.
推荐阅读
- google-cloud-platform - Dialogflow:未找到 agentId 的代理元数据
- c++ - 从项目 CMakeLists.txt 链接相互依赖的库?
- javascript - 我可以从 JavaScript 中的某个单词中切出一个字符串,不管它前面有多少个字符/单词?
- javascript - 在 XSL 模板中包含带有冒号的 JS 语法
- github - 更新预定的 yml 文件
- html - 低分辨率阴影
- javascript - 带有存储数据的 Firebase 存储上下文
- c# - 使用相同的按钮删除项目
- python - remove elements from a list based on condition in pandas dataframe
- html - 具有空内容的 CSS 网格布局(高度)