在with
語句中創建的變量範圍在with
塊之外(請參閱:Variable defined with with-statement available outside of with-block?)。但是,當我運行下面的代碼:爲什麼__del__在with塊的結尾被調用?
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.__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
我的問題是,爲什麼是Foo.__del__
這裏所說的,如果with
語句不會創建新的執行範圍?
另外,如果連接的__del__
方法是所謂的第二with
塊,我不明白爲什麼my_curs1.connection
仍然是開放後(見上文# line 2
)。
可能重複的[我可以使用語句與MySQLdb.Connection對象?](http://stackoverflow.com/questions/11751703/can-i-use-with-statement-with-mysqldb-connection-object) – tzaman
誠誠,請參閱@ tzaman的鏈接以回答您的第二個問題,並從您的問題中刪除該部分。將一個問題保存到一個問題有助於保持StackOverflow的整潔,並使人們能夠更快地找到答案。謝謝! – CodeMouse92
@tzaman這個問題是3歲,它的答案是不正確的。 – Air