我正在使用 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__and的返回值__unicode__被强制为str或者unicode取决于运行哪个魔术方法。
但是,如果我们这样做:
>>> 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。
str所以,我的问题是,当和unicode被调用时实际发生了什么?__str__和__unicode__中使用str和的返回值要求是unicode什么?