对于具有以下 init 方法的DB类:
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在
内部为无更新:修复输入方法以返回数据库对象。但需要有关如何调用它的帮助:
def __enter__(self, dbprops):
return DB(dbprops)
使用单个参数调用它显然不起作用:
with DB(dbprops) as db:
TypeError: __enter__() takes exactly 2 arguments (1 given)
现在我不遵循,因为“自我”应该自动填写..