with Point(3, 4) as pt:
print 'distance: ', pt.get_distance()
# output
initialize x and y # 调用了 __init__ 方法
Entering context # 调用了 __enter__ 方法
distance: 5.0 # 调用了 get_distance 方法
Exiting context # 调用了 __exit__ 方法
with Point(3, 4) as pt:
pt.get_length() # 访问了对象不存在的方法
# output
initialize x and y
Entering context
Exiting context
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-216-ab4a0e6b6b4a> in <module>()
1 with Point(3, 4) as pt:
----> 2 pt.get_length()
AttributeError: 'Point' object has no attribute 'get_length'
from math import sqrt, pow
class Point(object):
def __init__(self, x, y):
print 'initialize x and y'
self.x, self.y = x, y
def __enter__(self):
print "Entering context"
return self
def __exit__(self, type, value, traceback):
print "Exception has been handled"
print "Exiting context"
return True
def get_distance(self):
distance = sqrt(pow(self.x, 2) + pow(self.y,2 ))
return distance
with Point(3, 4) as pt:
pt.get_length() # 访问了对象不存在的方法
# output
initialize x and y
Entering context
Exception has been handled
Exiting context
file = open('somefile', 'r')
try:
for line in file:
print line
finally:
file.close() # 确保关闭文件
with open('somefile', 'r') as file:
for line in file:
print line
from contextlib import contextmanager
@contextmanager
def point(x, y):
print 'before yield'
yield x * x + y * y
print 'after yield'
with point(3, 4) as value:
print 'value is: %s' % value
# output
before yield
value is: 25
after yield