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

edited Dec 19, 2018 by Anirudh 107 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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,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
1,213 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 in Python by Omkar
• 67,000 points
35 views
0 votes
2 answers

how to print the current time using python?

print(datetime.datetime.today()) READ MORE

answered Feb 14 in Python by Shashank
• 1,350 points
28 views
+2 votes
11 answers

How to print array/ list without brackets in python?

name=["a","b","c"] print (', '.join(name)) It will simply take all ...READ MORE

answered Apr 18, 2018 in Python by aayushi
• 750 points
14,628 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
67 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 345 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.