class Fp:
def __enter__(self):
print('进入')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('退出', exc_type, exc_val, exc_tb)
def print_name(self):
print('this is my name')
def get_obj():
return Fp()
if __name__ == "__main__":
with get_obj() as fp:
fp.print_name()
如上图代码所示,with as获取到的fp为一个Fp类型的对象。
使用with机制,在开启是调用__enter__方法,as 后边的fp是__enter__函数的返回值。with语句块结束时调用__exit__方法。