简体   繁体   English

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

[英]How can printing an object result in different output than both str() and repr()?

I was testing some code on the interpreter and I noticed some unexpected behavior for the sqlite3.Row class. 我在解释器上测试了一些代码,我注意到了sqlite3.Row类的一些意外行为。

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 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>

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. 我认为sqlite3.Row必须是tuple的子类,但我仍然不明白幕后可能导致这种行为的是什么。 Can anyone explain this? 有谁能解释一下?

This was tested on Python 2.5.1, not sure if the behavior is the same for other Python versions. 这是在Python 2.5.1上测试的,不确定其他Python版本的行为是否相同。

Not sure whether or not this matters, but the row_factory attribute for my Connection was set to sqlite3.Row . 不确定这是否重要,但我的Connectionrow_factory属性设置为sqlite3.Row

PySqlite provides the special native hook for print , but it doesn't implement __repr__ or __str__ . PySqlite提供了特殊的原生钩print ,但它没有实现__repr____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 请参阅pysqlite源代码: https//github.com/ghaering/pysqlite/blob/master/src/row.c#L241和python docs: http//docs.python.org/c-api/typeobj.html#tp_print

s = str(tuple(row))

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: 例如,如果您想要轻松记录行,则非常有用,如下所示:

logging.debug(tuple(user_row))

Works because rows are iterable. 可以工作,因为行是可迭代的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM