gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:13:51 25 4
gpt4 key购买 nike

我在解释器上测试了一些代码,我注意到 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 必须是 tuple 的子类,但我仍然不明白幕后究竟发生了什么可能导致这种行为。谁能解释一下?

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

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

最佳答案

PySqlite 为 print 提供了特殊的原生钩子(Hook),但它没有实现 __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

关于python - 打印对象如何产生与 str() 和 repr() 不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7920284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com