问题描述
在调用 repr 时是否可以更改 int 型对象转换为字符串的方式? pprint.pformat ,这样
Is there any way of changing the way a int-type object is converted to string when calling repr or pprint.pformat, such that
repr(dict(a=5, b=100))
会给出 {a:0x5,b :0x64} 而不是 {a:5,b:100} ?
我想可以将 int 类型的子类化:
I suppose subclassing the int type would be an option:
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 函数对于保持按需完成和一起工作。此外,这显然会对性能产生影响。
But as you can see, the preprocess_for_repr function is rather unpleasant to keep "as-complete-as-needed" and to work with. Also, the obvious performance implications.
推荐答案
您应该能够猴子修补 pprint 模块以所需的方式打印整数,但这并不是一个好方法。
You should be able to monkey patch the pprint module to have integers print the way you want, but this isn't really a good approach.
如果您只是在寻找更好的表示形式,用于调试的整数,IPython拥有自己的漂亮打印机,可通过其模块:
If you're just looking for a better representation of integers for debugging, IPython has its own pretty printer that is easily customizable through its pretty module:
In [1]: from IPython.lib import pretty In [2]: pretty.for_type(int, lambda n, p, cycle: p.text(hex(n))) Out[2]: <function IPython.lib.pretty._repr_pprint> In [3]: 123 Out[3]: 0x7b In [4]: x = [12] In [5]: x Out[5]: [0xc] In [6]: pretty.pretty(x) Out[6]: '[0xc]'
您可以在链接文档中详细了解这三个参数。
You can read more about the three parameters in the linked documentation.
这篇关于覆盖__repr__或pprint int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!