对于以下具有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")
异常: 在with语句中,Db为None
更新: 修复了enter方法以返回DB对象。但需要帮助调用它:
def __enter__(self, dbprops):
return DB(dbprops)
只使用一个参数调用它似乎不起作用:
with DB(dbprops) as db:
TypeError: __enter__() takes exactly 2 arguments (1 given)
现在我不明白,因为“self”应该是自动填充的。
__init__()
之外的任何地方去做它呢? - Ignacio Vazquez-Abrams