zoukankan      html  css  js  c++  java
  • python with as的用法

    以下为转载https://www.cnblogs.com/DswCnblog/p/6126588.html

    with。。as。。一个使用场景是文件处理,你需要获取一个文件句柄,从文件中读取数据,然后关闭文件句柄。

    普通的文件处理如下:

    1 file = open("/tmp/foo.txt")
    2 data = file.read()
    3 file.close()#文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的

    由于文件读写时都有可能产生IOError,一旦出错,后面的f.close()就不会调用。所以,为了保证无论是否出错都能正确地关闭文件,我们可以使用try ... finally来实现:

    1 file = open("/tmp/foo.txt")
    2 try:
    3     data = file.read()
    4 finally:
    5     file.close()

    但是还有一个更简洁的实现,就是用with as

    1 with open("/tmp/foo.txt") as file:
    2     data = file.read()

    with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。

     1 class Sample:
     2     def __enter__(self):
     3         print "In __enter__()"
     4         return "Foo"
     5  
     6     def __exit__(self, type, value, trace):
     7         print "In __exit__()"
     8  
     9 def get_sample():
    10     return Sample()
    11  
    12 with get_sample() as sample:
    13     print "sample:", sample

    运行如下:

    1 In __enter__()
    2 sample: Foo
    3 In __exit__()

    运行过程:

    1. __enter__()方法被执行,返回的对象赋值给变量'sample'

    3. 执行代码块,打印变量"sample"的值为 "Foo"

    4. __exit__()方法被调用

    with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数- val, type 和 trace。 这些参数在异常处理中相当有用。我们来改一下代码,看看具体如何工作的。

     
    class Sample:
        def __enter__(self):
            return self
     
        def __exit__(self, type, value, trace):
            print "type:", type
            print "value:", value
            print "trace:", trace
     
        def do_something(self):
            bar = 1/0
            return bar + 10
     
    with Sample() as sample:
        sample.do_something()

    这个例子中,with后面的get_sample()变成了Sample()。这没有任何关系,只要紧跟with后面的语句所返回的对象有__enter__()和__exit__()方法即可。此例中,Sample()的__enter__()方法返回新创建的Sample对象,并赋值给变量sample。

    代码执行后:

     1 bash-3.2$ ./with_example02.py
     2 type: <type 'exceptions.ZeroDivisionError'>
     3 value: integer division or modulo by zero
     4 trace: <traceback object at 0x1004a8128>
     5 Traceback (most recent call last):
     6   File "./with_example02.py", line 19, in <module>
     7     sample.do_something()
     8   File "./with_example02.py", line 15, in do_something
     9     bar = 1/0
    10 ZeroDivisionError: integer division or modulo by zero

    实际上,在with后面的代码块抛出任何异常时,__exit__()方法被执行。正如例子所示,异常抛出时,与之关联的type,value和stack trace传给__exit__()方法,因此抛出的ZeroDivisionError异常被打印出来了。开发库时,清理资源,关闭文件等等操作,都可以放在__exit__方法当中。

    因此,Python的with语句是提供一个有效的机制,让代码更简练,同时在异常产生时,清理工作更简单。

  • 相关阅读:
    CC3000 SmartConfig
    谈谈几个月以来开发android蓝牙4.0 BLE低功耗应用的感受
    CC3000 SPI接口编程介绍
    cc3000+LM3S9B96
    CC3000 主机驱动API介绍
    Wi-FiR CC3000 模块
    修改远程桌面连接端口及修改端口号后如何连接!
    电脑网线/水晶头的连接方法(A类,B类)
    快速切换IP的批处理!
    IE打开报错,提示该内存不能为read的解决办法!
  • 原文地址:https://www.cnblogs.com/saolv/p/8452030.html
Copyright © 2011-2022 走看看