Python的字符串和Unicode强制/魔术函数是如何工作的?



我使用的是Python版本:2.7.3。

在Python中,我们使用魔术方法__str____unicode__来定义strunicode在自定义类中的行为:

>>> class A(object):
  def __str__(self):
    print 'Casting A to str'
    return u'String'
  def __unicode__(self):
    print 'Casting A to unicode'
    return 'Unicode'

>>> a = A()
>>> str(a)
Casting A to str
'String'
>>> unicode(a)
Casting A to unicode
u'Unicode'

该行为表明__str____unicode__的返回值被强制为strunicode,具体取决于运行哪个魔术方法。

但是,如果我们这样做:

>>> class B(object):
  def __str__(self):
    print 'Casting B to str'
    return A()
  def __unicode__(self):
    print 'Casting B to unicode'
    return A()

>>> b = B()
>>> str(b)
Casting B to str
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    str(b)
TypeError: __str__ returned non-string (type A)
>>> unicode(b)
Casting B to unicode
Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    unicode(b)
TypeError: coercing to Unicode: need string or buffer, A found

调用str.mro()unicode.mro()表示它们都是basestring的子类。然而,__unicode__也允许返回buffer对象,它直接继承object而不继承basestring

所以,我的问题是,当strunicode被调用时,实际发生了什么?在strunicode中使用__str____unicode__的返回值要求是什么?

然而,__unicode__也允许返回缓冲区对象,这

这是不对的。unicode()可以转换字符串或缓冲区。这是使用默认编码将传递的参数转换为unicode的"最佳尝试"(这就是为什么它说强制)。它将始终返回一个unicode对象。

所以,我的问题是,当str和unicode叫什么?__str__和的返回值要求是什么__unicode__用于str和unicode?

__str__应该返回对象的非正式的、人性化的字符串表示形式。当有人在你的对象上使用str(),或者当你的对象是print语句的一部分时,就会调用这个函数。

__unicode__应该总是返回一个 unicode对象。如果没有定义此方法,则调用__str__,然后将结果强制转换为unicode(通过将其传递给unicode())。

在第二个示例中,您返回无效对象,这就是您看到错误消息的原因。由于副作用,您的第一个示例似乎适用于__unicode__,但它也没有正确编写。

文档中的数据模型部分值得一读,以获得有关这些"神奇方法"的更多信息和细节。

最新更新