zoukankan      html  css  js  c++  java
  • python语法学习第九天--else和with语句

    else:

    while/for else:正常执行完循环(非break)执行else中代码

    try else:未捕捉到异常,执行else中代码

     

    with:

    语法格式:

    with open('666.txt') as f:

            f.read()

    执行顺序:

    先对紧跟with后的语句求值,返回对象的__enter__()被调用,as后的变量将被赋值为这个方法的返回值,当with后代码被全部执行完或者遇到异常需要退出之后,将调用前面返回对象的__exit__()

    __enter__(self)

    __exit__(self,type,value,trace)

    优点

    with使代码更简洁优雅

    ①监控异常:print(type)可以打印出抛出的异常

    ②处理异常

    def __exit__(self,type,value,traceback):

            return isinstance(value,TypeError)

    会跳过所有的TypeError,而会正常抛出其他异常

    ③清理资源,关闭文件等操作也被放在__exit()__方法中

  • 相关阅读:
    C++ 实现简单快速排序
    LEETCODE 198. House Robber
    leetcode 174
    GIT 版本的回退
    unorderd_map 自定义键值及哈希函数的重载
    互斥锁 形成死锁实例
    leetcode 300
    LeetCode 62
    LeetCode 122
    SVN提交,强制注释
  • 原文地址:https://www.cnblogs.com/code-fun/p/11768817.html
Copyright © 2011-2022 走看看