【问题标题】:With statement in python is returning None object even though __init__ method works即使 __init__ 方法有效,python 中的 With 语句也返回 None 对象
【发布时间】:2013-05-20 22:15:25
【问题描述】:

对于具有以下 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 在里面没有

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

  def __enter__(self, dbprops):
    return DB(dbprops)

使用单个参数调用它显然不起作用:

 with DB(dbprops) as db:

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

现在我不关注了,因为“self”应该是自动填写的..

【问题讨论】:

    标签: python with-statement


    【解决方案1】:

    context manager protocol__enter__()__exit__() 方法处理;前者必须返回要赋值的值。

    【讨论】:

    • 我明白了。我如何避免 initenter 之间的代码重复毕竟并非所有客户端都会使用“with”:它们可以直接实例化
    • 连接分配 (conn)。即应该在哪里完成(最好只有一个地方)
    • 为什么除了__init__() 之外,您还需要在其他任何地方执行此操作?
    • 这是目前正在执行的地方。因此,您对 enter 的回答似乎不再是决定因素:如果是,请进一步解释。 - 它已经到位(我将该内容添加到 OP,因为它被忽略了)
    • facepalm def __enter__(self): return self
    猜你喜欢
    • 1970-01-01
    • 2022-11-04
    • 2021-12-10
    • 2011-02-14
    • 2019-04-01
    • 1970-01-01
    • 2019-12-12
    • 2021-08-13
    • 2011-10-26
    相关资源
    最近更新 更多