【发布时间】:2014-05-16 23:40:09
【问题描述】:
我试图使用 Python 装饰器来捕获异常并记录异常。
import os.path
import shutil
class log(object):
def __init__(self, f):
print "Inside __init__()"
self.f = f
def __call__(self, *args):
print "Inside __call__()"
try:
self.f(*args)
except Exception:
print "Sorry"
@log
def testit(a, b, c):
print a,b,c
raise RuntimeError()
if __name__ == "__main__":
testit(1,2,3)
效果很好
Desktop> python deco.py
Inside __init__()
Inside __call__()
1 2 3
Sorry
问题是当我尝试使用 doctest 进行测试时
@log
def testit(a, b, c):
"""
>>> testit(1,2,3)
"""
print a,b,c
raise RuntimeError()
if __name__ == "__main__":
import doctest
doctest.testmod()
似乎什么都没有发生。
Desktop> python deco2.py
Inside __init__()
这有什么问题?
【问题讨论】:
标签: python decorator python-decorators doctest