Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

python - 在现代Python中声明自定义异常的正确方法?(Proper way to declare custom exceptions in modern Python?)

What's the proper way to declare custom exception classes in modern Python?

(在现代Python中声明自定义异常类的正确方法是什么?)

My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.

(我的主要目标是遵循其他异常类具有的任何标准,以便(例如)我捕获到异常中的任何工具都会打印出我包含在异常中的任何多余字符串。)

By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things.

(“现代Python”是指可以在Python 2.5中运行但对于Python 2.6和Python 3. *是“正确”的方式。)

And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.

(所谓“自定义”,是指一个Exception对象,该对象可以包含有关错误原因的其他数据:字符串,也许还包括与该异常相关的其他任意对象。)

I was tripped up by the following deprecation warning in Python 2.6.2:

(我在Python 2.6.2中被以下弃用警告绊倒了:)

>>> class MyError(Exception):
...     def __init__(self, message):
...         self.message = message
... 
>>> MyError("foo")
_sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6

It seems crazy that BaseException has a special meaning for attributes named message .

(BaseException对于名为message属性有特殊含义似乎很疯狂。)

I gather from PEP-352 that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden?

(我从PEP-352收集到,该属性确实在2.5中有特殊含义,因此他们想弃用该属性,所以我猜想现在禁止使用该名称(以及一个人)。)

Ugh.

(啊。)

I'm also fuzzily aware that Exception has some magic parameter args , but I've never known how to use it.

(我也模糊地知道Exception有一些魔术参数args ,但是我从来不知道如何使用它。)

Nor am I sure it's the right way to do things going forward;

(我也不确定这是前进的正确方法。)

a lot of the discussion I found online suggested they were trying to do away with args in Python 3.

(我在网上发现的很多讨论都表明他们正在尝试消除Python 3中的args。)

Update: two answers have suggested overriding __init__ , and __str__ / __unicode__ / __repr__ .

(更新:有两个答案建议覆盖__init____str__ / __unicode__ / __repr__ 。)

That seems like a lot of typing, is it necessary?

(好像要打很多笔,有必要吗?)

  ask by Nelson translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe I missed the question, but why not:

(也许我错过了这个问题,但是为什么不呢?)

class MyException(Exception):
    pass

Edit: to override something (or pass extra args), do this:

(编辑:要覆盖某些内容(或传递额外的args),请执行以下操作:)

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super(ValidationError, self).__init__(message)

        # Now for your custom code...
        self.errors = errors

That way you could pass dict of error messages to the second param, and get to it later with e.errors

(这样,您可以将错误消息的字典传递给第二个参数,并在以后使用e.errors到达它。)


Python 3 Update: In Python 3+, you can use this slightly more compact use of super() :

(Python 3更新:在Python 3+中,您可以使用对super()这种更为紧凑的用法:)

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super().__init__(message)

        # Now for your custom code...
        self.errors = errors

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...