为什么python str.format不调用str()

Jam*_*Lin 4 python

我有以下课程

class A(object):
  def __unicode__(self):
    return u'A'

  def __str__(self):
    return 'AA'

>>> u"{}".format(A())
u'A'
>>> "{}".format(A())
'AA'
>>> str(A())
'AA'
Run Code Online (Sandbox Code Playgroud)

根据文件,

"Harold是一个聪明的{0!s}"##首先在参数上调用str()

为什么这仍然回归你'不'u'AA'?

>>> u"{0!s}".format(A())
u'A'
Run Code Online (Sandbox Code Playgroud)

我希望它和它一样

>>> u"{}".format(str(A()))
u'AA'
Run Code Online (Sandbox Code Playgroud)

Blc*_*ght 5

我认为这是一个(次要的)文档错误.str.format呼吁str,如果您通过!s在格式字符串代码,但unicode.format调用unicode来代替.

文档可能是用Python 3编写的,其中所有字符串都是Unicode并!s始终调用str.整个新的格式化系统从Python 3.0反向移植到Python 2.6中,并且在文档中忽略了一些含糊不清的内容并不令人震惊.