How to print objects of class using print function in Python?

0 votes

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.

Dec 3, 2018 in Python by Anirudh
• 2,080 points

edited Dec 19, 2018 by Anirudh 27,021 views

1 answer to this question.

0 votes

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}

Hope this helps!

answered Dec 3, 2018 by Nymeria
• 3,520 points

edited Dec 19, 2018 by Nymeria

Related Questions In Python

0 votes
0 answers

How to print square of first 100 natural numbers using iterations in python?

Can you make a program with nested ...READ MORE

Jul 22, 2019 in Python by Waseem
• 4,540 points
101 views
+1 vote
1 answer

How to print first character of each word in upper case of a string in Python

You can use split() using space as ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
4,846 views
0 votes
1 answer

How to check latest change time of each file using glob in python?

You can get the changing time from ...READ MORE

answered Jan 2, 2019 in Python by Omkar
• 69,020 points
169 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,210 views
0 votes
0 answers
+4 votes
6 answers
0 votes
1 answer

How to get all related Django model objects in Python?

This actually gives you the property names ...READ MORE

answered Nov 14, 2018 in Python by Nymeria
• 3,520 points

edited Dec 18, 2018 by Nymeria 2,598 views