参考如下博客。

https://www.cnblogs.com/DswCnblog/p/6126588.html

 

#!/usr/bin/env python
# with_example02.py
 
class Sample:
    def __enter__(self):
        print "go to enter():"
        return self
 
    def __exit__(self, type, value, trace):
        print "go to exit():"
        print "type:", type
        print "value:", value
        print "trace:", trace
 
    def do_something(self):
        print "go to do_something():"
        bar = 1/0
        return bar + 10
 
with Sample() as sample:
    sample.do_something()

 

 

运行结果:

 

posted on 2018-02-25 23:11  爱编程的小兵  阅读(198)  评论(0编辑  收藏  举报