Python3,从自定义异常中调用super的__init__ [英] Python3, calling super's __init__ from a custom exception

查看:37
本文介绍了Python3,从自定义异常中调用super的__init__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 3 中创建了自定义异常,所有代码都运行良好.但是有一件事我无法理解,那就是为什么我需要将消息发送到 Exception 类的 __init__() 以及它如何将自定义异常转换为该字符串消息当我尝试打印异常时,因为 Exception 甚至 BaseException 中的代码没有做太多.

I have created custom exception in python 3 and the over all code works just fine. But there is one thing I am not able to wrap my head around is that why do I need to send my message to the Exception class's __init__() and how does it convert the Custom exception into that string message when I try to print the exception since the code in the Exception or even the BaseException does not do much.

不太明白为什么要从自定义异常中调用 super().__init__() ?

Not quite able to understand why call the super().__init__() from custom exception?

推荐答案

这样您的自定义异常就可以从与 BaseException 对象相同的实例属性开始,包括 value 属性,存放异常信息,其他一些方法如__str__需要用到该属性,允许异常对象直接转为字符串.您可以跳过在子类的 __init__ 中调用 super().__init__ ,而是根据需要自行初始化所有必要的属性,但是这样您就不会利用类继承的主要好处之一.始终调用 super().__init__ 除非您有非常具体的理由不重用任何父类的实例属性.

This is so that your custom exceptions can start off with the same instance attributes as a BaseException object does, including the value attribute, which stores the exception message, which is needed by certain other methods such as __str__, which allows the exception object to be converted to a string directly. You can skip calling super().__init__ in your subclass's __init__ and instead initialize all the necessary attributes on your own if you want, but then you would not be taking advantage of one of the key benefits of class inheritance. Always call super().__init__ unless you have very specific reasons not to reuse any of the parent class's instance attributes.

这篇关于Python3,从自定义异常中调用super的__init__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆