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

edited Dec 19, 2018 by Anirudh 128 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,500 points

edited Dec 19, 2018 by Nymeria

Related Questions In Python

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,120 points
0 votes
1 answer
0 votes
2 answers

how to print the current time using python?

print( READ MORE

answered Feb 14 in Python by Shashank
• 1,350 points
+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 128 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,500 points

edited Dec 18, 2018 by Nymeria 413 views