Python中with的用法

作者: lattle | 来源:发表于2017-10-06 19:37 被阅读336次

第一次遇到with是在文件那一章,with的作用是就是会自动关掉文件管道。

with open('path','读写模式‘) as f:
    do something

这一部分就等价于

f = open('path','读写模式')
do something
f.close()

第二次是在数据库连接,连接池那里。使用的基本思想大致是with所求值的对象必须有一个enter()方法和一个exit()方法。下面给一个简单的例子去说明使用with的时候做了哪些操作

class Sample:
    def __enter__(self):
        print "In __enter__()"
        return "Foo"
    def __exit__(self, type,value, trace):
        print "In__exit__()"
    
    def get_sample():
        return Sample()
with get_sample() as sample:
    print(sample)
  1. with开始,enter()方法被执行
  2. enter()方法返回的值 - 这个例子中是Foo,赋值给变量sample
  3. 执行代码块,打印变量sample的值为 Foo
  4. exit()方法被调用 with真正强大之处是它可以处理异常。注意到Sample类的exit方法有三个参数- val, typetrace。 这些参数在异常处理中相当有用。
class Sample:
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(exc_type)
        print(exc_val)
        print(exc_tb)
    def doSomething(self):
        a = 1/0
        return a
    def getSample():
        return Sample()
if __name__ == '__main__':
    with getSample() as sample:
        sample.doSomething()

这段代码的执行结果是

/usr/bin/python3.5 /home/zionhuang/data/awesome-python3-webapp/test/test8.py
<class 'ZeroDivisionError'>
division by zero
<traceback object at 0x7fbb5c091d48>
Traceback (most recent call last):
File "/home/zionhuang/data/awesome-python3-webapp/test/test8.py", line 23, in <module>
sample.doSomething()
File "/home/zionhuang/data/awesome-python3-webapp/test/test8.py", line 14, in doSomething
a = 1/0
ZeroDivisionError: division by zero
Process finished with exit code 1

结果头三句加黑的分别是val, typetrace这三个参数在出现异常时的值
常抛出时,与之关联的typevaluestack trace传给exit()方法,因此抛出的ZeroDivisionError异常被打印出来了。开发库时,清理资源,关闭文件等等操作,都可以放在exit方法当中。
因此,Pythonwith语句是提供一个有效的机制,让代码更简练,同时在异常产生时,清理工作更简单。

相关文章

  • 2022-08-18 node 与 python 交互

    node与python交互,可以使用 python-shell 。 用法: node中: python: 更多用法...

  • python 判断 循环 包 模块 函数

    标签 : python 判断 python中是没有switch这个用法的,实现这个用法最简单的就是上面的if......

  • Python笔记setdefault用法

    Python字典中setdefault的用法: Python 字典 setdefault() 方法和get()方法...

  • Python笔记

    [python 中的[::-1]] - 反转 这个是python的slice notation的特殊用法。a = ...

  • Python中with的用法

    第一次遇到with是在文件那一章,with的作用是就是会自动关掉文件管道。 这一部分就等价于 第二次是在数据库连接...

  • Python中in的用法

    有时候要判断一个数是否在一个序列里面,这时就会用到in运算符来判断成员资格,如果条件为真时,就会返回true,条件...

  • python中with的用法

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接...

  • python中%的用法

    1. 打印字符串 print (“His name is %s”%(“Aviad”)) 效果: 2.打印整数 pr...

  • python 中 with的用法

    with 语句使用于对资源进行访问的场合,确保不管使用过程是否发生异常都会执行必要的"清理"操作,释放资源,比如文...

  • python中*的用法

    一个变量名之前加号,表示把变量里的元素直接传进来作为参数。比如:test(args):* 的作用其实就是把序列 a...

网友评论

    本文标题:Python中with的用法

    本文链接:https://www.haomeiwen.com/subject/ymyryxtx.html