4-12 with上下文协议

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

你可能感兴趣的:(4-12 with上下文协议)