with的本质 __enter__(self)和__exit__(self,exc_type,exc_val,exc_tb):

#_*_ encoding: utf-8 _*_   @author: ty  hery   2019/12/20


# 打开文件对象
f = open('03.txt','w')
# 2,向文件写入内容
try:
    f.write('去你大爷的\n')
    print("写入成功了")
except Exception:
    print("写入失败了")
    pass
finally:
    # 3,关闭文件
    f.close()

f = open('01.txt','wb') # 等同于下面的with open
# with是上下文管理器,内部的代码全部都在with的监管之下运行的
with open('03.txt','ab') as f:   # 在f对象中含有__enter__,和__exit__方法,with调用这些方法,注意字节格式的不认识\n,不会换行
    f.write(b'qunidayede hello flask 01\n')
    f.write(b'qunidayede hello flask 02\n')
    f.write(b'qunidayede hello flask 03\n\n')
    f.write(b'qunidayede hello flask 04\n\n')
    f.write(b'qunidayede hello flask 05\n\n')

class Foo(object):
    def __enter__(self):
        '''进入with语句的时候被with调用'''
        print('enter called')

    def __exit__(self,exc_type,exc_val,exc_tb):
        '''离开with语句的时候被with调用'''
        print('exit called')
        print('exc_type: %s' %exc_type)
        print('exc_val: %s' %exc_val)
        print('exc_tb: %s' %exc_tb)


with Foo() as  foo:
    print('hello python ')
    a =1/0
    print('hello end')
posted @ 2021-04-12 23:16  ty1539  阅读(121)  评论(0编辑  收藏  举报