IPython忽略对象的

我写了一个defaultdict的子类,为了在交互式会话中定制它的外观,我给了它自己的__repr__方法。

在常规的Python会话中,按预期工作:

Python 3.5.0 (default, Sep 20 2015, 11:28:25) 
[GCC 5.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict
>>> class Foo(defaultdict):
...   def __repr__(self):
...     return 'foo_repr'
... 
>>> foo = Foo()
>>> foo
foo_repr

......但在IPython中它并没有:

In [1]: from collections import defaultdict

In [2]: class Foo(defaultdict):
   ...:     def __repr__(self):
   ...:         return 'foo_repr'
   ...:     

In [3]: foo = Foo()

In [4]: foo
Out[4]: defaultdict(None, {})

In [5]: repr(foo), str(foo)
Out[5]: ('foo_repr', 'foo_repr')

IPython在这里做什么,我该如何阻止它?

编辑:定义_repr_pretty_帮助:

In [1]: from collections import defaultdict

In [2]: class Foo(defaultdict):
    def __repr__(self):
        return 'foo_repr'
    def _repr_pretty_(self, p, cycle):
        p.text('repr_foo_pretty')
   ...:         

In [3]: foo = Foo()

In [4]: foo
Out[4]: repr_foo_pretty

但我还是不太明白发生了什么事。 显然, _repr_pretty之前没有在任何基类中定义过。 IPython如何使用defaultdict__repr__而不是Foo的,为什么它会在defaultdict发生,而不是其他的?

链接地址: http://www.djcxy.com/p/28311.html

上一篇: IPython ignores object's

下一篇: Python prints memory address instead of a list when using