Search code examples
pythonclassoopinstanceinstantiation

How to make class instances not look like '<__main__.Animal at 0x1f053e6abc8>


Let's say I have a list of class instances, and when I call it in Python it looks like this:

[<__main__.Animal at 0x1f053e6abc8>,
 <__main__.Animal at 0x1f049e3f848>,
 <__main__.Animal at 0x1f0532e8d08>,
 <__main__.Animal at 0x1f053e6a1c8>]

Is there something I could add to the code inside the classes to make them instead look like this below?

[Lion,
 Gorilla,
 Tiger,
 Baboon]

Solution

  • Implement the __repr__ method for your class. It should return a string. If, for example your class has a "name" attribute, you can just:

    def __repr__(self): return self.name