解决方案如下所示:
class CustomException(Exception):
def __init__(self, *args, **kwargs):
default_message = 'This is a default message!'
if args:
super().__init__(*args, **kwargs)
else:
super().__init__(default_message, **kwargs)
一个等效但更简洁的解决方案是:
class CustomException(Exception):
def __init__(self, *args, **kwargs):
default_message = 'This is a default message!'
if not args: args = (default_message,)
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(CustomException, self)
替换super()
。
现在运行:
>>> raise CustomException
将输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CustomException: This is a default message!
并运行:
raise CustomException('This is a custom message!')
将输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CustomException: This is a custom message!
这是前两个解决方案的代码将产生的输出。最后一个解决方案不同之处在于,如果至少使用一个参数调用它,如:
raise 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
因为它不允许在引发CustomException时传递任何参数。