Python with as :
Context Management Protocol(上下文管理协议):包含方法__enter()和__exit(),支持该协议的对象要实现这两个方法。上下文管理器(Context Manager):支持上下文管理协议的对象,这种对象实现了__enter()__ 和__exit()__ 方法。
用下述代码做理解,debug查看执行过程
# -*- coding: UTF-8 -*-
import re,sys,os,time
class Example:
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print "type:", type
print "value:", value
print "trace:", trace
def sum(self):
num = 666
return num + 10
with Example() as example:
example.sum()