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