python with妙用

class aa():
    def bb(self):
        print("hhhh")
        return "hello world"

    def __enter__(self): # 必须有__enter__
        print("enter")
        return self

    def cc(self):
        print("www")

    def __exit__(self, exc_type, exc_val, exc_tb): # 必须有结束__exit__
        print("exit")

def ll():
    with aa() as a:
        return a.bb()

res = ll()
print(res)

 

结果:

enter
hhhh
exit
hello world

 

posted @ 2017-08-26 18:07  我当道士那儿些年  阅读(177)  评论(0编辑  收藏  举报