打印对象如何产生与 str() 和 repr() 不同的输出? [英] How can printing an object result in different output than both str() and repr()?

查看:24
本文介绍了打印对象如何产生与 str() 和 repr() 不同的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<预><代码>>>>print row # 行对象像元组一样打印(你'字符串',)>>>print str(row) # 为什么这与上面的输出不匹配?<sqlite3.Row 对象在 0xa19a450>>>>row # 通常这将是一个对象的代表(你'字符串',)>>>print repr(row) # 但是 repr(row) 也是不同的!<sqlite3.Row 对象在 0xa19a450>

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

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

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

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

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.

解决方案

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

这篇关于打印对象如何产生与 str() 和 repr() 不同的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆