打印对象如何会导致与 str() 和 repr() 不同的输出?
我正在解释器上测试一些代码,我注意到 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>
我认为 sqlite3.Row
必须是元组
,但我仍然不确切地了解可能导致这种行为的幕后发生的事情。谁能解释一下吗?
这是在 Python 2.5.1 上测试的,不确定其他 Python 版本的行为是否相同。
不确定这是否重要,但是 row_factory
我的 Connection
属性设置为 sqlite3.Row
。
I was testing some code on the interpreter and I noticed some unexpected behavior for the sqlite3.Row
class.
My understanding was that print obj
will always get the same result as print str(obj)
, and typing obj
into the interpreter will get the same result as print repr(obj)
, however this is not the case for 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>
I think sqlite3.Row
must be a subclass of tuple
, but I still don't understand exactly what is going on behind the scenes that could cause this behavior. Can anyone explain this?
This was tested on Python 2.5.1, not sure if the behavior is the same for other Python versions.
Not sure whether or not this matters, but the row_factory
attribute for my Connection
was set to sqlite3.Row
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PySqlite 为
print
提供了特殊的本机钩子,但它没有实现__repr__
或__str__
。我想说这有点错过了机会,但至少它解释了您所观察到的行为。请参阅 pysqlite 源代码: https://github.com/ghaering/ pysqlite/blob/master/src/row.c#L241
和 python 文档: http://docs.python.org/c-api/ typeobj.html#tp_print
PySqlite provides the special native hook for
print
, but it doesn't implement__repr__
or__str__
. I'd say that's a bit of a missed chance, but at least it explains the behavior you're observing.See pysqlite source: https://github.com/ghaering/pysqlite/blob/master/src/row.c#L241
And python docs: http://docs.python.org/c-api/typeobj.html#tp_print
如果您想要原始元组字符串表示形式,这是一种解决方法。
例如,如果您想轻松地记录行,则它很有用:
可以工作,因为行是可迭代的。
is a workaround if you want the original tuple string representation.
It is useful for example if you want to log the row easily as in:
Works because rows are iterable.