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 @   ty1539  阅读(130)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示