IPython ignores object's

I have written a subclass of defaultdict , and I gave it its own __repr__ method in order to customize its look in an interactive session.

In a regular Python session this works as expected:

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

... but in IPython it doesn't:

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')

What is IPython doing here and how can I stop it?

EDIT: defining _repr_pretty_ helps:

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

But I still don't quite understand what's going on. Obviously, _repr_pretty was not defined before on any of the base classes. How does IPython come to using the defaultdict 's __repr__ instead of Foo 's and why does it happen with defaultdict and not many others?

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

上一篇: 带上名字的组合

下一篇: IPython忽略对象的