Chinaunix首页 | 论坛 | 博客
  • 博客访问: 329927
  • 博文数量: 130
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 554
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-19 19:24
文章分类

全部博文(130)

文章存档

2016年(31)

2015年(16)

2014年(13)

2013年(70)

分类: LINUX

2016-02-26 13:49:17


点击(此处)折叠或打开

  1. #!/usr/local/bin/python
  2. # -*- coding:utf8 -*-


  3. import sys
  4. from contextlib import contextmanager


  5. #
  6. # Define an object could working with 'with' statement
  7. #
  8. @contextmanager
  9. def visitAll(*k):
  10.     a = []
  11.     for i in k:
  12.         a.append(i*2 - 1)
  13.     yield a # 生成一个迭代器

  14. with visitAll(1,2,3,4) as vlist:
  15.         print vlist

    output:
        [1, 3, 5, 7]

The  statement is used to wrap the execution of a block with methods defined by a context manager (see section ). This allows common ...... usage patterns to be encapsulated for convenient reuse.

with_stmt ::=  "with" with_item ("," with_item)* ":"  with_item ::=  ["as" ]

The execution of the  statement with one “item” proceeds as follows:

  1. The context expression (the expression given in the ) is evaluated to obtain a context manager.

  2. The context manager’s  is loaded for later use.

  3. The context manager’s  method is invoked.

  4. If a target was included in the  statement, the return value from  is assigned to it.

    Note

     

    The  statement guarantees that if the  method returns without an error, then  will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. See step 6 below.

  5. The suite is executed.

  6. The context manager’s  method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to . Otherwise, three  arguments are supplied.

    If the suite was exited due to an exception, and the return value from the  method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the  statement.

    If the suite was exited for any reason other than an exception, the return value from  is ignored, and execution proceeds at the normal location for the kind of exit that was taken.

With more than one item, the context managers are processed as if multiple  statements were nested:

with A() as a, B() as b: suite 

is equivalent to

with A() as a: with B() as b: suite

阅读(741) | 评论(0) | 转发(0) |
0

上一篇:gcov useage

下一篇:常见排序算法详解

给主人留下些什么吧!~~