Python print 没有使用 __repr__、__unicode__ 或 __str__ 作为 unicode 子类?

2023-11-21

Python print 没有使用__repr__, __unicode__ or __str__打印时我的 unicode 子类。关于我做错了什么的任何线索吗?

这是我的代码:

使用 Python 2.5.2(r252:60911,2009 年 10 月 13 日,14:11:59)

>>> class MyUni(unicode):
...     def __repr__(self):
...         return "__repr__"
...     def __unicode__(self):
...         return unicode("__unicode__")
...     def __str__(self):
...         return str("__str__")
...      
>>> s = MyUni("HI")
>>> s
'__repr__'
>>> print s
'HI'

我不确定这是否是上述的准确近似值,但仅供比较:

>>> class MyUni(object):
...     def __new__(cls, s):
...         return super(MyUni, cls).__new__(cls)
...     def __repr__(self):
...         return "__repr__"
...     def __unicode__(self):
...         return unicode("__unicode__")
...     def __str__(self):
...         return str("__str__")
...
>>> s = MyUni("HI")
>>> s
'__repr__'
>>> print s
'__str__'

[已编辑...] 这听起来像是获取 isinstance(instance, basestring) 并提供对 unicode 返回值的控制的字符串对象的最佳方法,并且使用 unicode repr 是...

>>> class UserUnicode(str):
...     def __repr__(self):
...         return "u'%s'" % super(UserUnicode, self).__str__()
...     def __str__(self):
...         return super(UserUnicode, self).__str__()
...     def __unicode__(self):
...         return unicode(super(UserUnicode, self).__str__())
...
>>> s = UserUnicode("HI")
>>> s
u'HI'
>>> print s
'HI'
>>> len(s)
2

The _str_ and _repr_上面没有向这个示例添加任何内容,但其想法是显式地显示一个模式,并根据需要进行扩展。

只是为了证明这种模式授予控制权:

>>> class UserUnicode(str):
...     def __repr__(self):
...         return "u'%s'" % "__repr__"
...     def __str__(self):
...         return "__str__"
...     def __unicode__(self):
...         return unicode("__unicode__")
... 
>>> s = UserUnicode("HI")
>>> s
u'__repr__'
>>> print s
'__str__'

想法?


问题是print不尊重__str__ on unicode子类。

From 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)返回 true 如果v的类型是unicode 或子类。因此,这段代码直接编写 unicode 对象,无需咨询__str__.

注意子类化str并压倒一切__str__按预期工作:

>>> class mystr(str):
...     def __str__(self): return "str"
...     def __repr__(self): return "repr"
... 
>>> print mystr()
str

就像打电话一样str or 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 中的一个错误。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python print 没有使用 __repr__、__unicode__ 或 __str__ 作为 unicode 子类? 的相关文章

  • 如何仅选择数组中的第一列并对其求和?

    这是我的代码 import numpy as np contrainte1 1080 0 65 minutes tous les jours contrainte2 720 0 55 minutes du lundi au vendredi
  • python blpapi安装错误

    我试图根据 README 中的说明为 python 安装 blpapi 3 5 5 但是在运行时 python setup py install 我收到以下错误 running install running build running b
  • 如何使用 Twython 将 oauth_callback 值传递给 oauth/request_token

    Twitter 最近刚刚强制执行以下规定 1 您必须通过oauth callbackoauth request token 的值 这不是可选的 即使您已经在 dev twitter com 上设置了一个 如果您正在执行带外 OAuth 请通
  • 无法使用 Python 循环分页 API 响应

    所以 我对这个感到摸不着头脑 使用 HubSpot 的 API 我需要获取我客户的 门户 帐户 中所有公司的列表 遗憾的是 标准 API 调用一次只能返回 100 家公司 当它返回响应时 它包含两个参数 使分页响应成为可能 其中之一是 ha
  • 将相同的 Patch 实例添加到 matplotlib 中的多个子图中

    我正在尝试将补丁的相同实例添加到 matplotlib 中的多个轴 这是最小的例子 import matplotlib pyplot as mpl plt import matplotlib patches as mpl patches f
  • 如何解决CDK CLI版本不匹配的问题

    我收到以下错误 此 CDK CLI 与您的应用程序使用的 CDK 库不兼容 请将CLI升级到最新版本 云程序集架构版本不匹配 支持的最大架构版本为 8 0 0 但发现为 9 0 0 发出后cdk diff命令 我确实跑了npm instal
  • 如何在每次运行 python 程序时添加新列

    我希望我的表的第一列作为卷号 第二列作为名称 每当我运行 python 程序时 我想在表中添加一列日期 在这个新列中 我想填充从 user list 获得的列表将包含值 P A P P 等 如何处理 我尝试首先通过 alter 命令添加一列
  • 多个列表和大小的所有可能排列

    在 python 中使用以下命令很容易计算简单的排列itertools permutations https docs python org 3 library itertools html itertools permutations 你
  • 如何不断地将 STDOUT 发送到我的 python TCP 服务器?

    我有简单的 python echo 服务器 它使用套接字 并向客户端回显随机数 我有另一个程序 每 2 秒将值打印到标准输出 如果它只是一个脚本 我可以像这样重定向 stdout python script py 并像这样在脚本中获取它da
  • 在 Scala 中创建 Java 对象

    我有一个 Java 类 Listings 我在 Java MapReduce 作业中使用它 如下所示 public void map Object key Text value Context context throws IOExcept
  • 如何在自定义 django 命令中抽象出命令代码

    我正在我的应用程序下编写自定义 django 命令management commands目录 目前我在该目录中有 6 个不同的文件 每个文件都有不同的命令来解决独特的需求 然而 有一些实用程序是它们所共有的 抽象出这些公共代码的最佳方法是什
  • 如何使用 Python 实现并行 gzip 压缩?

    使用python压缩大文件 https stackoverflow com questions 9518705 big file compression with python给出了一个很好的例子来说明如何使用例如bz2 纯粹用 Pytho
  • Pandas 中的数据透视表小计

    我有以下数据 Employee Account Currency Amount Location Test 2 Basic USD 3000 Airport Test 2 Net USD 2000 Airport Test 1 Basic
  • 获取 python 模块的 2 个独立实例

    我正在与以非 OO 方式编写的 python 2 x API 进行交互 它使用模块全局范围来处理一些内部状态驱动的东西 在它不再是单例的情况下需要它 并且修改原始代码 不是我们的 不是一个选择 如果不使用单独解释器的子进程运行 有什么方法可
  • 从 python 文件调用 Julia 函数

    我能够创建一个 docker 环境 然后按照这个线程我有一个用 Julia 编写的高性能函数 如何从 Python 中使用它 https stackoverflow com questions 64241264 i have a high
  • 给定一个字符串,如何删除所有重复的连续字母?

    如何从字符串中删除两个连续的字母 例如 a str hii thherre 应该成为 hi there 我尝试这样做 a str join sorted set a str key a str index 但是 我得到 hi ter 是的
  • 如何通过 Selenium 内部的文本查找按钮(Python)?

    我有以下三个按钮 我不知道如何获取其中的文本 例如异常值 我试过browser find element by link text Outliers click 但出现 无法找到元素 错误 我该怎么做 See find element by
  • 具有重复值的 Sqlite 列

    就说专栏吧aSQLite 数据库的非常重复 始终有相同的 4 个值 其他值可能稍后出现 但不同值的数量将少于 1000 个 VALUES hello world it s a shame to store this str many tim
  • Pandas 2 个字段中唯一值的数量

    我正在尝试查找覆盖 2 个字段的唯一值的数量 例如 一个典型的例子是姓氏和名字 我有一个数据框 当我执行以下操作时 我只获取每列的唯一字段数 在本例中为 最后一个 和 第一个 不是复合体 df Last Name First Name nu
  • 如何从Python枚举类中获取所有值?

    我正在使用 Enum4 库创建一个枚举类 如下所示 class Color Enum RED 1 BLUE 2 我要打印 1 2 作为某处的列表 我怎样才能实现这个目标 您可以执行以下操作 e value for e in Color

随机推荐