• 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('去你大爷的
    ')
        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调用这些方法,注意字节格式的不认识
    ,不会换行
        f.write(b'qunidayede hello flask 01
    ')
        f.write(b'qunidayede hello flask 02
    ')
        f.write(b'qunidayede hello flask 03
    
    ')
        f.write(b'qunidayede hello flask 04
    
    ')
        f.write(b'qunidayede hello flask 05
    
    ')
    
    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')
    
    写入自己的博客中才能记得长久
  • 相关阅读:
    文件路径与操作系统
    试验10
    shiyan9
    sql
    shiyan8
    iostream
    shiyan7
    CDMA
    试验6
    试验5
  • 原文地址:https://www.cnblogs.com/heris/p/14651105.html
Copyright © 2020-2023  润新知