例如,我有这个代码:
with MyClass() as x:
print 'I have only {0}'.format(x)
with MyClass() as y:
print 'I have {0} and {1}'.format(x, y)
print 'Again only {0}'.format(x)
x并且在退出相应的块y后都应该取消初始化。也不是. with_xyMyClass
__exit__只有三个参数,每个参数都是 None (如果没有提供异常)。
如何确定__exit__刚刚退出的块以及返回的值是什么__enter__?
(NB 代码应该是线程安全的)。
例子:
class MyClass(object):
def __enter__(self):
if moon_phase > 0:
return 123
else:
return 456
def __exit__(self):
number = what_was_returned_by_enter()
print 'End of block with', number
with MyClass() as x:
print x # 123
with MyClass() as y:
print x, 'and', y # 123 and 456
# printed "End of block with 456"
print x # 123
# printed "End of block with 123"