1. 类内有 __enter__ 和 __exit__ 方法的类被称为环境管理器ide
2. 可以用with语句进行管理的对象必须是环境管理器对象
3. __enter__ 将在进入with语句时调用并返回由 as 变量管理的对象blog
4. __exit__ 将在离开with时被调用,且能够用参数判断离开with语句时是否有异常发生,并作出相应的处理it
class Door:class
def open_door(self):变量
print("正在开门")方法
def close_door(self):im
print("正在关门")异常
def come_in(self):img
print("正在进人")
def __enter__(self):
self.open_door()
return self #对象被as绑定(开门的动做被c绑定)
def __exit__(self, exc_type, exc_val, exc_tb):
self.close_door()
if exc_type is None:
print("with语句正常退出")
else:
print("with语句异常退出",exc_value)
with Door() as c:
c.come_in()
3 / 0 #抛出一个异常
c.come_in()
__enter__语句在with执行时调用 open_door 动做,在with执行完毕调用__exit__语句里面的 close_door操做。判断语句检查类型并抛出状态