gpt4 book ai didi

python - 创建合作的异常(exception)

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:42 24 4
gpt4 key购买 nike

Python docs状态:

Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derivedfrom the Exception class, either directly or indirectly.

...

When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions.

来自Python’s super() considered super! :

Each level strips-off the keyword arguments that it needs so that the final empty dict can be sent to a method that expects no arguments at all (for example, object.init expects zero arguments)

假设我有以下 StudentValueErrorMissingStudentValue 异常。

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)

我想创建协作的异常。我有两个问题:

  1. 在这种情况下,Exception 类构造函数需要零个参数(空 dict),对吗?
  2. 我的示例是否违反了 LSP?

提供了接受的答案here继承自 ValueError

最佳答案

Exception 不接受任何关键字参数,它仅通过 *args 接受可变数量的位置参数,因此您需要更改 **kwargs*args。另外,我建议将 messageexpression*args 一起传递给 super() 调用。毕竟,这个示例可能不会违反 LSP:

class StudentValueError(Exception):
"""Base class exceptions for Student Values"""
def __init__(self, message='', *args):
super().__init__(message, *args)
self.message = message


class 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)

关于python - 创建合作的异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55210410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com