with上下文的实行是通过Python内置的魔法函数实现的
class Example:
def __enter__(self):
print("enter")
return self
def __exit__(self,exc_type,exc_val,exc_tb):
#释放资源
print("exit")
def do_something(self):
print("doing something")
with Example() as ex:
ex.do_something()
enter
doing something
exit