例如回來後,我有這樣的代碼:獲得通過__enter__在__exit__
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
塊退出後去初始化。 x
和y
也不是MyClass
的實例。
__exit__
只有三個參數,每個參數都是無(如果沒有提供異常)。
我如何確定__exit__
哪個塊剛剛退出,以及__enter__
返回的值是什麼?
(N.B.代碼應該是線程安全的)。
例子:
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"
只要保持跟蹤你通過將其存儲在一個實例變量返回的值。 – sloth