Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print instances of a class using print()?

I am learning the ropes in Python. When I try to print an object of class Foobar using the print() function, I get an output like this:

<__main__.Foobar instance at 0x7ff2a18c> 

Is there a way I can set the printing behaviour (or the string representation) of a class and its objects? For instance, when I call print() on a class object, I would like to print its data members in a certain format. How to achieve this in Python?

If you are familiar with C++ classes, the above can be achieved for the standard ostream by adding a friend ostream& operator << (ostream&, const Foobar&) method for the class.

like image 441
Ashwin Nanjappa Avatar asked Oct 08 '09 02:10

Ashwin Nanjappa


People also ask

What is the use of print () method?

print(): print() method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console.

How do you print a class object in Python?

In Python, this can be achieved by using __repr__ or __str__ methods. __repr__ is used if we need a detailed information for debugging while __str__ is used to print a string version for the users. Important Points about Printing: Python uses __repr__ method if there is no __str__ method.

How do I find the class of an instance?

To get the class name of an instance in Python: Use the type() function and __name__ to get the type or class of the Object/Instance.


1 Answers

>>> class Test: ...     def __repr__(self): ...         return "Test()" ...     def __str__(self): ...         return "member of Test" ...  >>> t = Test() >>> t Test() >>> print(t) member of Test 

The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

like image 140
Chris Lutz Avatar answered Oct 14 '22 17:10

Chris Lutz