自定义异常中的默认消息 – Python
发布时间:2020-12-20 11:02:46 所属栏目:Python 来源:网络整理
导读:我想在 Python中创建一个自定义异常,当没有任何参数引发时,它将打印一个默认消息. 案例: class CustomException(Exception): # some code here raise CustomException 并获得以下输出: Traceback (most recent call last): File "stdin",line 1,in module_
我想在
Python中创建一个自定义异常,当没有任何参数引发时,它将打印一个默认消息.
案例: >>> class CustomException(Exception): # some code here >>> raise CustomException 并获得以下输出: Traceback (most recent call last): File "<stdin>",line 1,in <module> __main__.CustomException: This is a default message! 解决方法
解决方案由以下代码给出:
class CustomException(Exception): def __init__(self,*args,**kwargs): default_message = 'This is a default message!' # if any arguments are passed... if args or kwargs: # ... 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) 一个等效但更简洁的解决方案是: class CustomException(Exception): def __init__(self,**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 not (args or kwargs): 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_message变量,您当然可以在上述每个解决方案中保存一行. 如果您希望代码与Python 2.7兼容,那么您只需将super()替换为super(CustomException,self). 现在运行: >>> raise CustomException 将输出: Traceback (most recent call last): File "<stdin>",in <module> __main__.CustomException: This is a default message! 和运行: raise CustomException('This is a custom message!') 将输出: Traceback (most recent call last): File "<stdin>",in <module> __main__.CustomException: This is a custom message! 这是前两个解决方案代码将产生的输出.最后一个解决方案的不同之处在于,使用至少一个参数调用它,例如: raise CustomException('This is a custom message!') 它将输出: Traceback (most recent call last): File "<stdin>",in <module> TypeError: __init__() takes 1 positional argument but 2 were given 因为它不允许任何参数在引发时传递给CustomException. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |