with 语法

作者: 爱吃葡萄冰的鲸 | 来源:发表于2017-05-23 18:59 被阅读10次

with 语句是从 Python 2.5 开始引入的一种与异常处理相关的功能

with如何工作?

  1. 紧跟with后面的语句被求值后,返回对象的 enter() 方法被调用,这个方法的返回值将被赋值给as后面的变量。
  2. 当with后面的代码块全部被执行完之后,将调用前面返回对象的 exit()方法。
#!/usr/bin/env python
# with_example01.py
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:", sample

运行代码,输出如下

bash-3.2$ ./with_example01.py
In __enter__()
sample: Foo
In __exit__()

正如你看到的: 1. enter()方法被执行 2. enter()方法返回的值 - 这个例子中是”Foo”,赋值给变量’sample’ 3. 执行代码块,打印变量”sample”的值为 “Foo” 4. exit()方法被调用 with真正强大之处是它可以处理异常。

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

#!/usr/bin/env python
# with_example02.py
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。

代码执行后:

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

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

摘抄自:http://blog.kissdata.com/2014/05/23/python-with.html

相关文章

  • GO语言gin框架实战-04-websocket链接

    1. 升级接口 1.1 语法 - 升级接口 语法 语法示例 - 关闭 语法 语法示例 - 接收前端信息 语法 语法...

  • 软帝学院:80道java基础部分面试题(四)

    Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语法,集...

  • JSON 语法

    JSON 语法是 JavaScript 语法的子集。 JSON 语法规则 JSON 语法是 JavaScript ...

  • art-template模板

    art-template同时支持两种模板语法:标准语法 和 原始语法 标准语法: {{ 数据 }}原始语法: <%...

  • Dart的一些语法糖(持续更新)

    语法糖 ?. 与 ?? dart 语法糖 ?. dart 语法糖 ??

  • dart语法7-泛型

    dart语法1dart语法2-内置类型dart语法3-函数dart语法4-操作符dart语法5-异常dart语法6...

  • dart语法8-库

    dart语法1dart语法2-内置类型dart语法3-函数dart语法4-操作符dart语法5-异常dart语法6...

  • dart语法10-生成器

    dart语法1dart语法2-内置类型dart语法3-函数dart语法4-操作符dart语法5-异常dart语法6...

  • dart语法9-异步

    dart语法1dart语法2-内置类型dart语法3-函数dart语法4-操作符dart语法5-异常dart语法6...

  • dart语法11

    dart语法1dart语法2-内置类型dart语法3-函数dart语法4-操作符dart语法5-异常dart语法6...

网友评论

    本文标题:with 语法

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