代码之家  ›  专栏  ›  技术社区  ›  Mikko Rantanen

Python的“with”语句与“with”。.as”

  •  17
  • Mikko Rantanen  · 技术社区  · 17 年前

    真的 在Python 2.5中。

    dbao.getConnection()

    conn = dbao.getConnection()
    with conn:
        # Do stuff
    

    with dbao.getConnection() as conn:
        # Do stuff
    

    conn Cursor .光标是从哪里来的

    3 回复  |  直到 10 年前
        1
  •  18
  •   pantsgolem    17 年前

    with babby() as b:
        ...
    

    b = babby()
    with b:
        ...
    

    要了解原因,以下是上下文管理器的实现方式:

    class babby(object):
        def __enter__(self):
            return 'frigth'
    
        def __exit__(self, type, value, tb):
            pass
    

    b __enter__ 'frigth' ,在您的情况下,它是数据库游标。

    在第二种情况下, b 是上下文管理器对象本身。

        2
  •  30
  •   dF.    17 年前

    一般来说,由 as 一部分 with 语句将是返回的任何内容 __enter__ method of the context manager .

        3
  •  1
  •   iny    17 年前

    从with语句的角度来看,您给出的两个块是相同的。您也可以将as添加到第一个中并获取光标。

    http://docs.python.org/whatsnew/2.5.html#pep-343-the-with-statement