zoukankan      html  css  js  c++  java
  • 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')
    
    写入自己的博客中才能记得长久
  • 相关阅读:
    数据库之01-数据库概述
    Bootstrap框架
    jQuery
    补充:html速查表
    BOM,DOM相关案例
    BOM,DOM
    函数,词法分析,内置对象和方法
    前端 之 JaveScript 基础语法: 数据类型; 运算符; 数据转换; 流程控制; 常用内置对象;
    favicon.ioc使用以及注意事项
    redux-undo
  • 原文地址:https://www.cnblogs.com/heris/p/14651105.html
Copyright © 2011-2022 走看看