案例:
>>> 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.
总结以上是内存溢出为你收集整理的自定义异常中的默认消息 – Python全部内容,希望文章能够帮你解决自定义异常中的默认消息 – Python所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)