打印对象如何产生与str()和repr()不同的输出?

And*_*ark 17 python sqlite

我在解释器上测试了一些代码,我注意到了这个sqlite3.Row类的一些意外行为.

我的理解是print obj总是得到相同的结果print str(obj),并且obj在解释器中输入将得到相同的结果print repr(obj),但是不是这样的情况sqlite3.Row:

>>> print row       # the row object prints like a tuple
(u'string',)
>>> print str(row)  # why wouldn't this match the output from above?
<sqlite3.Row object at 0xa19a450>

>>> row             # usually this would be the repr for an object
(u'string',)
>>> print repr(row) # but repr(row) is something different as well!
<sqlite3.Row object at 0xa19a450>
Run Code Online (Sandbox Code Playgroud)

我认为sqlite3.Row必须是它的子类tuple,但我仍然不明白幕后可能会导致这种行为的是什么.有谁能解释一下?

这是在Python 2.5.1上测试的,不确定其他Python版本的行为是否相同.

不确定这是否重要,但row_factory我的属性Connection设置为sqlite3.Row.

Ond*_*nde 12

PySqlite提供了特殊的本机钩子print,但它没有实现__repr____str__.我会说这是一个错失的机会,但至少它解释了你所观察到的行为.

请参阅pysqlite源代码:https://github.com/ghaering/pysqlite/blob/master/src/row.c#L241 和python docs:http://docs.python.org/c-api/typeobj.html#tp_print

  • 我在pysqlite的bugtracker中链接了这个主题:http://code.google.com/p/pysqlite/issues/detail?id = 4 (3认同)
  • 很好找!似乎sqlite开发人员反对建议,这可能是为什么在更多地方没有看到这一点.从文档:"类型永远不应该以产生不同于tp_repr或tp_str的输出的方式实现tp_print"和"建议不要定义tp_print,而是依靠tp_repr和tp_str进行打印". (2认同)