问题是,print
不尊重__str__
的unicode
子类。
来自PyFile_WriteObject
,由print
:
int
PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
{
...
if ((flags & Py_PRINT_RAW) &&
PyUnicode_Check(v) && enc != Py_None) {
char *cenc = PyString_AS_STRING(enc);
char *errors = fobj->f_errors == Py_None ?
"strict" : PyString_AS_STRING(fobj->f_errors);
value = PyUnicode_AsEncodedString(v, cenc, errors);
if (value == NULL)
return -1;
PyUnicode_Check(v)
如果v
类型为unicode
或子类, 则返回true 。因此,该代码无需咨询即可直接编写unicode对象__str__
。
请注意,子类化str
和重写__str__
按预期工作:
>>> class mystr(str):
... def __str__(self): return "str"
... def __repr__(self): return "repr"
...
>>> print mystr()
str
像调用str
或unicode
显式一样:
>>> class myuni(unicode):
... def __str__(self): return "str"
... def __repr__(self): return "repr"
... def __unicode__(self): return "unicode"
...
>>> print myuni()
>>> str(myuni())
'str'
>>> unicode(myuni())
u'unicode'
我相信这可以解释为目前实现的Python错误。