在现代Python中声明自定义异常类的正确方法是什么?我的主要目标是遵循标准的其他异常类,因此(例如)我在异常中包含的任何额外字符串都会被捕获异常的任何工具打印出来.
通过"现代Python",我指的是将在Python 2.5中运行的东西,但对于Python 2.6和Python 3*的处理方式来说是"正确的".而"自定义"我指的是一个Exception对象,它可以包含有关错误原因的额外数据:一个字符串,也许还有一些与异常相关的任意对象.
我被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
Run Code Online (Sandbox Code Playgroud)
看起来很疯狂,BaseException
对于名为的属性具有特殊含义message
.我从PEP-352收集到该属性确实在2.5中有特殊含义他们试图弃用,所以我猜这个名字(而且仅此一个)现在被禁止了?啊.
我也模糊地意识到它Exception
有一些神奇的参数args
,但我从来不知道如何使用它.我也不确定这是向前发展的正确方法; 我在网上发现的很多讨论都表明他们试图在Python 3中废除args.
更新:两个答案建议覆盖__init__
,和__str__
/ __unicode__
/ __repr__
.这似乎很多打字,是否有必要?
思考练习:编写采用正则表达式模式或字符串完全匹配的Python函数的“最佳”方法是什么:
import re
strings = [...]
def do_search(matcher):
"""
Returns strings matching matcher, which can be either a string
(for exact match) or a compiled regular expression object
(for more complex matches).
"""
if not is_a_regex_pattern(matcher):
matcher = re.compile('%s$' % re.escape(matcher))
for s in strings:
if matcher.match(s):
yield s
Run Code Online (Sandbox Code Playgroud)
那么,实施的思路is_a_regex_pattern()
呢?