相关疑难解决方法(0)

解释Python的'__enter __'和'__exit__'

我在某人的代码中看到了这个.这是什么意思?

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()
Run Code Online (Sandbox Code Playgroud)
from __future__ import with_statement#for python2.5 

class a(object):
    def __enter__(self):
        print 'sss'
        return 'sss111'
    def __exit__(self ,type, value, traceback):
        print 'ok'
        return False

with a() as s:
    print s


print s
Run Code Online (Sandbox Code Playgroud)

python oop with-statement

314
推荐指数
6
解决办法
21万
查看次数

Python数据库连接关闭

使用下面的代码让我打开一个连接,如何关闭?

import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 

csr = conn.cursor()  
csr.close()
del csr
Run Code Online (Sandbox Code Playgroud)

python database-connection

48
推荐指数
4
解决办法
7万
查看次数

标签 统计

python ×2

database-connection ×1

oop ×1

with-statement ×1