使用Python中的with语句返回None对象,尽管__init__方法有效

6

对于以下具有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”应该是自动填充的。
1个回答

11

我明白了。我该如何避免在__init__和__enter__之间出现代码重复呢?毕竟,并不是所有客户端都会使用“with”:他们可能会直接实例化。 - WestCoastProjects
连接(conn)的分配。即应该在哪里进行(最好只有一个地方)。 - WestCoastProjects
为什么你需要在__init__()之外的任何地方去做它呢? - Ignacio Vazquez-Abrams
那就是目前正在进行的地方。所以,关于_enter_的答案似乎已经不再是一个区别制造者:如果是的话,请进一步解释。-它已经就位了(我将该内容添加到OP中,因为它被忽略了)。 - WestCoastProjects
必须返回值以进行赋值。 - Ignacio Vazquez-Abrams
5
面掌上*,“def enter(self):”的意思是“定义一个__enter__方法,并返回self”。 - Ignacio Vazquez-Abrams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接