Python 的“with"语句与“with .. as" [英] Python's 'with' statement versus 'with .. as'
问题描述
刚刚因为差异而脱掉头发,我想知道 Python 2.5 中真正有什么不同.
Having just pulled my hair off because of a difference, I'd like to know what the difference really is in Python 2.5.
我有两个代码块(dbao.getConnection()
返回一个 MySQLdb 连接).
I had two blocks of code (dbao.getConnection()
returns a MySQLdb connection).
conn = dbao.getConnection()
with conn:
# Do stuff
和
with dbao.getConnection() as conn:
# Do stuff
我认为这些会产生相同的效果,但显然不是因为后一个版本的 conn
对象是 Cursor
.游标从何而来,有没有办法以某种方式将变量初始化和 with 语句结合起来?
I thought these would have the same effect but apparently not as the conn
object of the latter version was a Cursor
. Where did the cursor come from and is there a way to combine the variable initialization and with statement somehow?
推荐答案
一般来说,由 with
语句的 as
部分分配的值将是上下文管理器的 __enter__
方法返回的任何内容.
In general terms, the value assigned by the as
part of a with
statement is going to be whatever gets returned by the __enter__
method of the context manager.
这篇关于Python 的“with"语句与“with .. as"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!