【发布时间】:2011-05-06 23:22:58
【问题描述】:
在引发异常后,我正在尝试覆盖 Python 中 Exception 子类的打印输出,但我没有运气让我的覆盖被实际调用。
def str_override(self):
"""
Override the output with a fixed string
"""
return "Override!"
def reraise(exception):
"""
Re-raise an exception and override its output
"""
exception.__str__ = types.MethodType(str_override, exception, type(exception))
# Re-raise and remove ourselves from the stack trace.
raise exception, None, sys.exc_info()[-1]
def test():
"""
Should output "Override!" Actually outputs "Bah Humbug"
"""
try:
try:
raise Exception("Bah Humbug")
except Exception, e:
reraise(e, "Said Scrooge")
except Exception, e:
print e
知道为什么这实际上并没有覆盖 str 方法吗?反省实例变量表明该方法实际上被该方法覆盖,但它就像 Python 只是拒绝通过 print 调用它。
我在这里错过了什么?
【问题讨论】: