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,070 points

edited Dec 19, 2018 by Anirudh 2,934 views

1 answer to this question.

0 votes

It can be done as shown below:

class Element:
    def __init__(self, name, symbol, number): = 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)


__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 in Python by Waseem
• 4,470 points
0 votes
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
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 in Python by Omkar
• 67,660 points
0 votes
1 answer
+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 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 337 views
+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 769 views