【发布时间】:2017-05-27 18:21:03
【问题描述】:
我正在尝试在交互式 shell 中工作时实现漂亮的分析结果(在我的情况下为IPython)。这是某种映射,顺序对我来说也很重要,所以我尝试从OrderedDict 继承并覆盖__repr__ 方法,但这种方法不起作用。最小测试示例:
In[1]: from collections import OrderedDict
In[2]: class Result(OrderedDict):
def __repr__(self):
if self.keys():
report = []
for k, v in self.items():
report.append(k.ljust(10) + ': ' + repr(v))
return "\n".join(report)
else:
return self.__class__.__name__ + "()"
In[3]: res = Result()
res['all'] = 10
res['some'] = 11
res
Out[3]: Result([('all', 10), ('some', 11)])
但是当我从dict (class Result(dict):) 继承时,这种方法按预期工作,结果如下:
Out[3]: all : 10
some : 11
但不能保证顺序。我不知道,为什么第一种方法不起作用?
编辑:
Python 3.6.1
IPython 6.0.0
【问题讨论】:
-
我无法重现您的结果。
-
我无法在 python 2.7 中重现 - 你在哪个版本?
-
这个问题好像只出现在IPython中。
-
IPythonshell 对我来说是如此永久的工具。我什至不明白 - 问题的根源在哪里。谢谢。
标签: python inheritance ordereddictionary