Print objects of a Class in Python

avatar

Borislav Hadzhiev

Last updated: Sep 13, 2022

banner

Photo from Unsplash

Print objects of a Class in Python #

Define the __str__() method to print objects of a class. The __str__() method is called by str(object) and the built-in format() and print() functions and returns the informal string representation of the object.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return f'Name: {self.name}' bobby = Employee('bobbyhadz', 500) # ✅ print object of class print(bobby) # 👉️ Name: bobbyhadz # ✅ print dictionary containing an object's attributes and values print(str(bobby.__dict__)) # 👉️ {'name': 'bobbyhadz', 'salary': 100}

We defined the __str__() method to be able to print the class's objects.

The __str__() method is called by str(object) and the built-in format() and print() functions and returns the informal string representation of the object.

Any time you use the class instance in a formatted string literal, with thestr.format() or print() functions, the output of the __str__() method gets used.

If you need to print an object's attributes and values, access its __dict__ attribute.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return f'Name: {self.name}' bobby = Employee('bobbyhadz', 500) print(str(bobby.__dict__)) # 👉️ {'name': 'bobbyhadz', 'salary': 100}

The __dict__ attribute returns a dictionary containing the object's properties and values.

Make sure to return a string from the __str__() method, otherwise a TypeError is raised.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return self.salary # 👈️ returned int, but only strings allowed bobby = Employee('bobbyhadz', 500) # ⛔️ TypeError: __str__ returned non-string (type int) print(bobby)

To return the employee's salary from the __str__() method, we have to use the str() class to convert the value to a string.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return str(self.salary) bobby = Employee('bobbyhadz', 500) print(bobby) # 👉️ 500

The __str__() method is called if you use the object in a formatted string literal or with the str.format() method.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return str(self.salary) bobby = Employee('bobbyhadz', 500) result = f'Salary: {bobby}' print(result) # 👉️ Salary: 500

The __str__() method should return a string that is a human-readable representation of the object.

There is also a __repr__() method that can be used in a similar way.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name bobby = Employee('bobbyhadz', 500) print(bobby) # 👉️ bobbyhadz

The __repr__ method is called by the repr() function and is usually used to get a string that can be used to rebuild the object using the eval() function.

If the class doesn't have the __str__() method defined, but has __repr__() defined, the output of __repr__() is used instead.

A good way to illustrate the difference between __str__() and __repr__() is to use the datetime.now() method.

main.py
import datetime # 👇️ using __str__() print(datetime.datetime.now()) # 👉️ 2022-09-13 19:24:30.537917 # 👇️ using __repr__() # 👉️ datetime.datetime(2022, 9, 13, 19, 24, 30, 537942) print(repr(datetime.datetime.now())) result = eval('datetime.datetime(2022, 9, 13, 19, 24, 30, 537942)') print(result) # 👉️ 2022-09-13 19:24:30.537942

When we used the print() function, the __str__() method in the datetime class got called and returned a human-readable representation of the date and time.

When we used the repr() function, the __repr__() method of the class got called and returned a string that can be used to recreate the same state of the object.

We passed the string to the eval() function and created a datetime object with the same state.

Note that implementing the __repr__() method in this way is not always necessary or possible.

Having the __str__() method return a human-readable string is sufficient most of the time.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.