创建合作的例外 [英] Creating exceptions that are co-operative

查看:144
本文介绍了创建合作的例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 文档状态:

The Python docs state:


程序可以通过创建新的异常
类来命名自己的异常(有关Python类的更多信息,请参见类)。
通常应该直接从Exception类派生,也可以直接从Exception类派生。

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.

... p>

...


在创建可能引发多个不同错误的模块时,
的常见做法是为$ b定义的异常创建基类$ b该模块,以及为不同错误条件创建特定异常类
的子类。

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的super()被认为是超级!


每个级别都剥离其所需的关键字参数,以便可以将
最终空字典发送给一个期望在$ b $没有参数的方法b全部(例如,对象。 init 期望参数为零)

假设我有以下 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:


  1. 在那种情况下, Exception 类构造函数期望零参数(空 dict ),对吗?

  2. 我的示例是否违反LSP?

  1. In that case, the Exception class constructor expects zero arguments (empty dict), correct?
  2. 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 = 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)

这篇关于创建合作的例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆