Область действия переменных, созданных в операторе with
, находится за пределами блока with
(см. -with-block">Переменная, определенная с помощью инструкции with, доступна вне блока 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__
вызывается перед печатью foo (в # 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
здесь а>. @air прав - связанный дубликат устарел - person J Richard Snape   schedule 06.10.2015__del__
вызывается, но могу сказать, что это вызвало обсуждение в чате Python — chat.stackoverflow. com/комнаты/6/питон - person J Richard Snape   schedule 06.10.2015