1. 类内有 __enter__ 和 __exit__ 方法的类被称为环境管理器

2. 能够用with语句进行管理的对象必须是环境管理器

3. __enter__ 将在进入with语句时调用并返回由 as 变量管理的对象

4. __exit__ 将在离开with时被调用,且可以用参数判断离开with语句时是否有异常发生,并做出相应的处理



class Door:

def open_door(self):

print("正在开门")

def close_door(self):

print("正在关门")

def come_in(self):

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操作。判断语句检查类型并抛出状态