对于具有以下init方法的数据库类:
class DB:
def __init__(self, dbprops):
self.dbprops = dbprops
self.conn = self.get_connection(self.dbprops)
debug("self.conn is %s" %self.conn)
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if not self.conn is None:
self.close()
对于调用它的客户端方法,如下所示:
with DB(self.dbprops) as db:
if not db:
raise Exception("Db is None inside with")
return db.get_cmdline_sql()
输出显示调试消息-因此成功调用了init方法:
File "./classifier_wf.py", line 28, in get_cmdline_mysql
raise Exception("Db is None inside with")
例外:Db在里面是None
更新:修复了enter方法以返回数据库对象的问题.但是需要有关如何调用它的帮助:
def __enter__(self, dbprops):
return DB(dbprops)
用单个参数调用它显然不起作用:
with DB(dbprops) as db:
TypeError: __enter__() takes exactly 2 arguments (1 given)
现在,我不再关注,因为应该自动填写“自我”.