p>...来自 Python的super()被认为是超级!:假设我有以下 StudentValueError 和 Mi ssingStudentValue 异常。class StudentValueError(Exception): """Base class exceptions for Student Values""" def __init__(self, message, **kwargs): super().__init__(**kwargs) self.message = message # You must provide at least an error message.class MissingStudentValue(StudentValueError): def __init__(self, expression, message, **kwargs): super().__init__(message, **kwargs) self.expression = expression def __str__(self): return "Message: {0} Parameters: {1}".format(self.message, self.expression)我想创建合作的例外。我有两个问题:I want to create exceptions that are co-operative. I have two questions: 在那种情况下, Exception 类构造函数期望零参数(空 dict ),对吗? 我的示例是否违反LSP?In that case, the Exception class constructor expects zero arguments (empty dict), correct?Does my example violate LSP? 此处提供的接受的答案继承自 ValueError 。The accepted answer provided here inherits from ValueError.推荐答案 例外不包含关键字参数,它只通过 * args 接受可变数量的位置参数,因此您需要将 ** kwargs 更改为 * args 。我也建议将消息和表达式与 * args 调用 super()。毕竟,该示例可能未违反LSP:Exception takes no keyword arguments, it takes only variable amount of positional parameters via *args, so you need to change **kwargs to *args. Also I would recommend to pass message and expression together with *args to super() call. After all, the example, which probably doesn't violate LSP:class StudentValueError(Exception): """Base class exceptions for Student Values""" def __init__(self, message='', *args): super().__init__(message, *args) self.message = messageclass MissingStudentValue(StudentValueError): def __init__(self, message='', expression='', *args): super().__init__(message, expression, *args) self.expression = expression def __str__(self): return "Message: {0} Parameters: {1}".format(self.message, self.expression)e = Exception('message', 'expression', 'yet_another_argument')print(e)e = StudentValueError('message', 'expression', 'yet_another_argument')print(e)e = MissingStudentValue('message', 'expression', 'yet_another_argument')print(e)e = MissingStudentValue()print(e) 这篇关于创建合作的例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-23 05:05