【发布时间】:2016-01-03 16:04:51
【问题描述】:
在with 语句中创建的变量的范围在with 块之外(参考:Variable defined with with-statement available outside of with-block?)。但是当我运行以下代码时:
class Foo:
def __init__(self):
print "__int__() called."
def __del__(self):
print "__del__() called."
def __enter__(self):
print "__enter__() called."
return "returned_test_str"
def __exit__(self, exc, value, tb):
print "__exit__() called."
def close(self):
print "close() called."
def test(self):
print "test() called."
if __name__ == "__main__":
with Foo() as foo:
print "with block begin???"
print "with block end???"
print "foo:", foo # line 1
print "-------- Testing MySQLdb -----------------------"
with MySQLdb.Connect(host="xxxx", port=0, user="xxx", passwd="xxx", db="test") as my_curs2:
print "(1)my_curs2:", my_curs2
print "(1)my_curs2.connection:", my_curs2.connection
print "(2)my_curs2.connection:", my_curs2.connection
print "(2)my_curs2.connection.open:", my_curs2.connection.open # line 2
输出显示在打印 foo 之前调用了 Foo.__del__(在上面的 # line 1):
__int__() called.
__enter__() called.
with block begin???
with block end???
__exit__() called.
__del__() called.
foo: returned_test_str
-------- Testing MySQLdb -----------------------
(1)my_curs2: <MySQLdb.cursors.Cursor object at 0x7f16dc95b290>
(1)my_curs2.connection: <_mysql.connection open to 'xxx' at 2609870>
(2)my_curs2.connection: <_mysql.connection open to 'xxx' at 2609870>
(2)my_curs2.connection.open: 1
我的问题是,如果with 语句没有创建新的执行范围,为什么在这里调用Foo.__del__?
另外,如果连接的__del__ 方法在第二个with 块中被调用,我不明白为什么my_curs1.connection 之后仍然打开(参见上面的# line 2)。
【问题讨论】:
-
Chengcheng,请参阅@tzaman 的链接以获取第二个问题的答案,并从您的问题中删除该部分。一个问题对一个问题有助于保持 StackOverflow 的整洁,并使人们能够更快地找到答案。谢谢!
-
@tzaman 这个问题有 3 年历史了,它的答案不正确。
-
是的 - 这是一个有趣的问题。
mysqldb上下文管理器 here 有更新的讨论。 @air 是对的 - 链接的副本已过期 -
@JRichardSnape 该帖子与我的不同。我知道为什么游标没有关闭。因为 with 语句不调用 close()。见这里stackoverflow.com/questions/5669878/…
标签: python mysql-python with-statement