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__(在上面的#第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__
方法?另外,如果第二个with
块中调用了连接的__del__
方法,我不明白为什么my_curs1.connection
之后仍然处于打开状态(请参见上面的# line 2
)。
mysqldb
上下文管理器的讨论 here。@air是正确的 - 链接的重复已经过时了。 - J Richard Snape__del__
,但我可以告诉你它在Python聊天室中引发了一些讨论 - http://chat.stackoverflow.com/rooms/6/python - J Richard Snape