python中的With语句返回None对象,即使_init__方法有效

python中的With语句返回None对象,即使_init__方法有效,python,with-statement,Python,With Statement,对于具有以下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

对于具有以下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,带有

更新:修复了返回DB对象的方法。但需要关于如何调用它的帮助:

  def __enter__(self, dbprops):
    return DB(dbprops)
使用单个参数调用它显然不起作用:

 with DB(dbprops) as db:

TypeError: __enter__() takes exactly 2 arguments (1 given)

现在我不跟随,因为“self”应该是自动填写的。

\uuuu enter\uuuu()
\uu exit\uuu()方法处理;前者必须返回要赋值的值。

我明白了。如何避免init和enter之间的代码重复毕竟不是所有客户端都会使用“with”:它们可能会实例化连接的直接分配(conn)。i、 e.应该在哪里做(最好只有一个地方)为什么除了在
\uuu init\uuuu()
之外的任何地方都要做?这就是目前正在做的事情。因此,您关于输入的回答似乎不再是一个差异制造者:如果是,请进一步解释。-它已经就位(我将该内容添加到OP中,因为它被忽略了)facepalm
def\uuuu enter\uuuuuu(self):
返回self