with
with 常用应用场景:
打开文件
申请一个锁
可以实现with 操作的,实现了两个方法 __enter__ 和 __exit__
class TestWith(object):
def __enter__(self):
print "entering"
def __exit__(self,exception_type,exception_value,exception_traceback):
print "exiting"
if exception_type is None:
print "everthing is ok"
else:
print "error happend : %s"%exception_value
with TestWith():
print "in here"
raise Exception("opps!")