自定义异常中的默认消息-Python
我想在Python中创建一个自定义异常,当在没有任何参数的情况下引发该异常时,它将打印一条默认消息 代码示例:自定义异常中的默认消息-Python,python,exception,Python,Exception,我想在Python中创建一个自定义异常,当在没有任何参数的情况下引发该异常时,它将打印一条默认消息 代码示例: 类自定义异常(异常): 传递一些代码 引发自定义异常() 并获得以下输出: Traceback (most recent call last): File "<stdin>", line 1, in <module> __main__.CustomException: This is a default message! 回溯(最近一
类自定义异常(异常):
传递一些代码
引发自定义异常()
并获得以下输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CustomException: This is a default message!
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
__main\uuuu.CustomException:这是一条默认消息!
以下代码给出了解决方案:
class CustomException(Exception):
def __init__(self, *args, **kwargs):
default_message = 'This is a default message!'
# if any arguments are passed...
# If you inherit from the exception that takes message as a keyword
# maybe you will need to check kwargs here
if args:
# ... pass them to the super constructor
super().__init__(*args, **kwargs)
else: # else, the exception was raised without arguments ...
# ... pass the default message to the super constructor
super().__init__(default_message, **kwargs)
一个等效但更简洁的解决方案是:
class CustomException(Exception):
def __init__(self, *args, **kwargs):
default_message = 'This is a default message!'
# if no arguments are passed set the first positional argument
# to be the default message. To do that, we have to replace the
# 'args' tuple with another one, that will only contain the message.
# (we cannot do an assignment since tuples are immutable)
# If you inherit from the exception that takes message as a keyword
# maybe you will need to check kwargs here
if not args: args = (default_message,)
# Call super constructor
super().__init__(*args, **kwargs)
一个更简洁但受限的解决方案是,您只能在没有参数的情况下引发CustomException:
class CustomException(Exception):
def __init__(self):
default_message = 'This is a default message!'
super().__init__(default_message)
当然,在上述每个解决方案中,如果只将字符串文本传递给构造函数,而不是使用default\u消息
变量,则可以保存一行
如果希望代码与Python 2.7兼容,那么只需将:super()
替换为super(CustomException,self)
现在运行:
>>> raise CustomException
将输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CustomException: This is a default message!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CustomException: This is a custom message!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes 1 positional argument but 2 were given
将输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CustomException: This is a default message!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CustomException: This is a custom message!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes 1 positional argument but 2 were given
它将输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CustomException: This is a default message!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CustomException: This is a custom message!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes 1 positional argument but 2 were given
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:\uuuu init\uuuuuu()接受1个位置参数,但提供了2个
因为它不允许在引发CustomException时将任何参数传递给CustomException。这是如何使用默认消息定义自定义异常的最简单解决方案,如果需要,可以覆盖该消息:
class CustomException(Exception):
def __init__(self, msg='My default message', *args, **kwargs):
super().__init__(msg, *args, **kwargs)
用法示例:
In [10]: raise CustomException
---------------------------------------------------------------------------
CustomException Traceback (most recent call last)
<ipython-input-10-259ae5202c8e> in <module>
----> 1 raise CustomException
CustomException: My default message
In [11]: raise CustomException()
---------------------------------------------------------------------------
CustomException Traceback (most recent call last)
<ipython-input-11-c1921a8781a6> in <module>
----> 1 raise CustomException()
CustomException: My default message
In [12]: raise CustomException('Foo bar')
---------------------------------------------------------------------------
CustomException Traceback (most recent call last)
<ipython-input-12-7efbf94f7432> in <module>
----> 1 raise CustomException('Foo bar')
CustomException: Foo bar
[10]中的:引发自定义异常
---------------------------------------------------------------------------
CustomException回溯(最近一次调用上次)
在里面
---->1提出客户例外
CustomException:我的默认消息
在[11]中:引发CustomException()
---------------------------------------------------------------------------
CustomException回溯(最近一次调用上次)
在里面
---->1.引发自定义异常()
CustomException:我的默认消息
在[12]中:引发自定义异常(“Foo-bar”)
---------------------------------------------------------------------------
CustomException回溯(最近一次调用上次)
在里面
---->1提出客户例外(“Foo-bar”)
自定义例外:Foo-bar
在对的回答中,这是声明自定义异常的一种非常好的方法:
class MyException(Exception):
"""Docstring here"""
如果要定义多个异常,可以使用Exception
的子类作为其异常的超类,将这些异常的docstring作为其默认消息:
class Doc_Default_Exception(Exception):
"""Subclass exceptions use docstring as default message"""
def __init__(self, msg=None, *args, **kwargs):
super().__init__(msg or self.__doc__, *args, **kwargs)
class MyException(Doc_Default_Exception):
"""Docstring here."""
raise MyException
输出:
Traceback (most recent call last):
File "C:\************************.py", line 9, in <module>
raise MyException
__main__.MyException: Docstring here
Traceback (most recent call last):
File "C:\************************.py", line 16, in <module>
raise MyException
__main__.MyException: Docstring here
输出:
Traceback (most recent call last):
File "C:\************************.py", line 9, in <module>
raise MyException
__main__.MyException: Docstring here
Traceback (most recent call last):
File "C:\************************.py", line 16, in <module>
raise MyException
__main__.MyException: Docstring here
回溯(最近一次呼叫最后一次):
文件“C:\***********************.py”,第16行,在
引起我的反感
__main.MyException:这里是Docstring
当然,应该使用描述性消息引发异常,但默认回退有时就足够了,如果编写正确,docstring就足够了。我认为这实际上是最好的答案。这非常有效,看起来很优雅。然而,我想指出的是,pylint对此不太满意,并称之为无用的超级委派