【问题标题】:Is __repr__ supposed to return bytes or unicode?__repr__ 应该返回字节还是 unicode?
【发布时间】:2018-06-24 16:03:48
【问题描述】:

在 Python 3 和 Python 2 中,__repr__ 应该返回字节还是 unicode?参考和报价将是理想的。

Here's some information 关于 2-3 的兼容性,但我没有看到答案。

【问题讨论】:

  • 我的猜测是它不应该返回 unicode,因为 repr() 应该用于程序员(而不是用户),并且某些控制台不支持 unicode。

标签: python python-3.x python-2.7 unicode repr


【解决方案1】:

类型是str(对于python2.x和python3.x):

>>> type(repr(object()))
<class 'str'>

必须如此,因为__str__ 默认调用__repr__,如果前者不存在,但__str__ 返回str

对于那些不知道的人,在 python3.x 中,str 是代表 unicode 的类型。在python2.x中,str是代表字节的类型。

【讨论】:

  • str 在 Python3 中是 unicode,在 Python2 中是字节。我相信 OP 正在寻找这些细节
  • @cowbert -- 不,str 在两者中都是 str。 Python3 没有 unicode 类型(就像 python2 没有字节类型一样)。从语义上讲,python3 的 str 与 python2.x 的 unicode 功能等效,如果这就是您要说的话...
  • @mgilson OP 清楚地询问 repr 是否返回具有字节或 unicode 表示的对象,并且显然想知道 Py2 与 Py3 的区别。在 Py3 中,str 是一个 unicode 对象。
  • 它的措辞可以更好。两者的类型都是str,但它们的含义完全不同......!
  • 另外有趣的是:__str__()__repr__() 的访问器都需要将返回类型设置为 str。在 Py3k 中,我尝试覆盖 __str__()__repr__() 以返回 b'' 和所有 print()(调用 __str__())、str()repr()(调用 __repr__() 将产生一个 @ 987654347@.
【解决方案2】:

两种语言都是str

Python 3.6.4 (default, Dec 21 2017, 18:54:30) 

>>> type(repr(()))
<class 'str'>

Python 2.7.14 (default, Nov  7 2017, 17:59:11) 
>>> type(repr(()))
<type 'str'>

(里面有一个元组。)

【讨论】:

    猜你喜欢
    • 2015-08-18
    • 2017-06-12
    • 2011-08-08
    • 2015-05-28
    • 2012-11-23
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多