How to print objects of class using print function in Python

605    Asked by CharlesParr in Python , Asked on Jul 19, 2021

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

<__main__.Foobar instance at 0x7ff2a18c>
For instance, when I call print() on a class object, I would like to print its data members in a certain format that is easy to grasp.

How to achieve this easily in Python? Appreciate some help.

Answered by Amit verma

It can be done as shown below: 

class Element:

    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number
    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)
And then,
elem = Element('my_name', 'some_symbol', 3)
print(elem)
produces
__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}
Important Points about python class print:
Python uses __repr__ method if there is no __str__ method. Example: class Test: def __init__( self , a, b): self .a = a. self .b = b. def __repr__( self ): ...
If no __repr__ method is defined then the default is used. Example: class Test: def __init__( self , a, b): self .a = a. self .b = b.
Hope this helps!


Your Answer

Interviews

Parent Categories