gpt4 book ai didi

python - 将 "NoneType object has no attribute"用于自定义上下文管理器时获取 "with ... as"

转载 作者:IT老高 更新时间:2023-10-28 22:15:07 24 4
gpt4 key购买 nike

我用 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')

但是,如果我尝试使用 with...as,我不会得到对 TestContext() 对象的引用。运行这个:

with TestContext() as t:
print t.test_number

引发异常'NoneType'对象没有属性'test_number'

我哪里错了?

最佳答案

假设您需要访问在 with 语句中创建的上下文管理器,__enter__ needs to return self .如果您不需要访问它,__enter__ 可以返回您想要的任何内容。

The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.

这会起作用。

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 - 将 "NoneType object has no attribute"用于自定义上下文管理器时获取 "with ... as",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34749943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com