0

Is there a way in Python to specify a custom print method (or equivalent) for a class? Borrowing a concept from the R language (and possibly others) what I would like it a way for the interpreter to know that when I type

obj

which is assumed to mean

print(obj)

it should use my custom method to print some details about the object, instead of telling me the type and memory address. Is there such a feature or similar in python?

Bogdanovist
  • 1,498
  • 2
  • 11
  • 20
  • 8
    Override `__str__` and `__repr__`. – Ashwini Chaudhary Sep 02 '13 at 04:47
  • Note that `obj` is not equivalent to `print(obj)`, even at the interactive prompt. If `obj` does not evaluate to `None`, Python will automatically print `repr(obj)`. – user2357112 Sep 02 '13 at 04:51
  • Thanks @AshwiniChaudhary, that's exactly what I'm looking for. The answer is provided in the question you refer to, but the questions themselves I think are different and probably not a duplicate, or maybe not? Either way thanks for enlightening me. – Bogdanovist Sep 02 '13 at 05:54
  • Side note: if you are using the IPython interpreter, then you can define also other `_repr_X_` methods that can return images/latex code etc. see [rich display](http://ipython.org/ipython-doc/dev/config/integrating.html#rich-display), and an [example notebook](http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%205%20-%20Rich%20Display%20System.ipynb). – Bakuriu Sep 02 '13 at 06:41

0 Answers0