python - 为 int 覆盖 __repr__ 或 pprint

标签 python python-3.x built-in

在调用reprpprint.pformat 时,是否有任何方法可以改变int 类型对象转换为字符串的方式,例如那个

repr(dict(a=5, b=100))

会给出 "{a: 0x5, b: 0x64}" 而不是 "{a: 5, b: 100}"?

我想继承 int 类型是一种选择:

class IntThatPrintsAsHex(int):
    def __repr__(self):
        return hex(self)

def preprocess_for_repr(obj):
    if isinstance(obj, dict):
        return {preprocess_for_repr(k): preprocess_for_repr(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [preprocess_for_repr(e) for e in obj]
    elif isinstance(obj, tuple):
        return tuple(preprocess_for_repr(e) for e in obj)
    elif isinstance(obj, int) and not isinstance(obj, bool):
        return IntThatPrintsAsHex(obj)
    elif isinstance(obj, set):
        return {preprocess_for_repr(e) for e in obj}
    elif isinstance(obj, frozenset):
        return frozenset(preprocess_for_repr(e) for e in obj)
    else:  # I hope I didn't forget any.
        return obj

print(repr(preprocess_for_repr(dict(a=5, b=100))))

但如您所见,preprocess_for_repr 函数很难保持“按需完成”和使用。此外,明显的性能影响。

最佳答案

int 是内置类型,您不能设置内置/扩展类型的属性(您不能覆盖或向这些类型添加新方法)。但是,您可以子类化 int 并覆盖 __repr__ 方法,如下所示:

 class Integer(int):
     def __repr__(self):
         return hex(self)

 x = Integer(3)
 y = Integer(100)

 # prints "[0x3, 0x64]"
 print [x,y]

Integer 的行为与 int 完全一样,除了 __repr__ 方法。您可以使用它索引列表、做数学等等。但是,除非您覆盖它们,否则数学运算将返回常规的 int 结果:

>>> print [x,y,x+1,y-2, x*y]
[0x3, 0x64, 4, 98, 300]

关于python - 为 int 覆盖 __repr__ 或 pprint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39095294/

相关文章:

python - 有没有办法在不使用 'in' 关键字的情况下知道元素列表是否在更大的列表中?

python - Pandas groupby 和 value_counts

python - 存储和散列密码 Flask - Python

python - 在 Python 类中使用属​​性导致 "maximum recursion depth exceeded"

python - 计算文本中的空格(将连续的空格视为一个)

php - 内置的 PHP 服务器日志在哪里?

python - 基本的 Python 文件搜索和 I/O

python - 如何使用python在mapreduce中的直方图(Graph)中获取结果?

robotframework - 机器人框架: BuiltIn library : Should Match : How to pass a pattern parameter correctly?

python - 有没有一种优雅的方法来检查是否可以在 numpy 数组中请求索引?