我用Python编写了一个简单的上下文管理器,用于处理单元测试(并尝试学习上下文管理器):
class TestContext(object):
test_count=1
def __init__(self):
self.test_number = TestContext.test_count
TestContext.test_count += 1
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, exc_traceback):
if exc_value == None:
print 'Test %d passed' %self.test_number
else:
print 'Test %d failed: %s' %(self.test_number, exc_value)
return True
如果我按如下方式编写测试,则一切正常。
test = TestContext()
with test:
print 'running test %d....' %test.test_number
raise Exception('this test failed')
但是,如果我尝试与... as一起使用,则不会获得对TestContext()对象的引用。运行此:
with TestContext() as t:
print t.test_number
引发异常
'NoneType' object has no attribute 'test_number'
。我要去哪里错了?
最佳答案
假设您需要访问在with
语句 __enter__
needs to return self
中创建的上下文管理器。如果您不需要访问它,__enter__
可以返回您想要的任何内容。
这会起作用。
class TestContext(object):
test_count=1
def __init__(self):
self.test_number = TestContext.test_count
TestContext.test_count += 1
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
if exc_value == None:
print 'Test %d passed' % self.test_number
else:
print 'Test %d failed: %s' % (self.test_number, exc_value)
return True
关于python - Python with…至于自定义上下文管理器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34749943/