您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python打印不是对Unicode子类使用__repr __,__ unicode__或__str__吗?

python打印不是对Unicode子类使用__repr __,__ unicode__或__str__吗?

问题是,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

调用strunicode显式一样:

>>> 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错误

python 2022/1/1 18:30:22 有395人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶