Print an object's attributes in Python

avatar

Borislav Hadzhiev

Last updated: Sep 13, 2022

banner

Photo from Unsplash

Print an object's attributes in Python #

Use the __dict__ attribute to print an object's attributes, e.g. print(my_object.__dict__). The __dict__ attribute returns a dictionary containing the object's properties and values.

main.py
class Employee(): def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # ✅ print object attributes and values attributes_and_values = bob.__dict__ # 👇️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100} print(attributes_and_values) # ------------------------------------------- # ✅ print object attributes only_attributes = list(bob.__dict__.keys()) print(only_attributes) # 👉️ ['id', 'name', 'salary'] # ------------------------------------------- # ✅ print object values only_values = list(bob.__dict__.values()) print(only_values) # 👉️ [1, 'bobbyhadz', 100] # ------------------------------------------- # ✅ print list of names of class's attributes # 👇️ ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] print(dir(Employee))

We used the __dict__ attribute to print an object's attributes.

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

You can use the dict.keys() and dict.values() methods if you only need the object's attribute or values.

If you need a list of the names of the object's attributes, use the dir() function.

main.py
class Employee(): def __init__(self, id, name, salary): # 👇️ instance variables self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # 👇️ ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'id', 'name', 'salary'] print(dir(bob))

The dir function returns a list of the names of the class's attributes, and recursively of the attribute of its base classes.

If you need to pretty print the attributes of the object, use the pprint() method.

main.py
from pprint import pprint class Employee(): def __init__(self, id, name, salary): # 👇️ instance variables self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # ['__class__', # '__delattr__', # '__dict__', # '__dir__', # '__doc__', # ... # ] pprint(dir(bob))

The pprint.pprint method prints the formatted representation of an object.

If you need to format the object's attributes into a string, use the str.join() method and a formatted string literal.

main.py
class Employee(): def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # # 👇️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100} print(bob.__dict__.items()) result = ', '.join(f'{key}={str(value)}' for key, value in bob.__dict__.items()) print(result) # 👉️ id=1, name=bobbyhadz, salary=100

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces - {expression}.

Alternatively, you can use the vars() function.

Print an object's attributes using vars() #

Use the vars() function to print an object's attributes, e.g. print(vars(my_object)). The vars() function returns a dictionary containing the object's properties and values.

main.py
class Employee(): def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # 👇️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100} print(vars(bob)) only_attributes = list(vars(bob).keys()) print(only_attributes) # 👉️ ['id', 'name', 'salary'] only_values = list(vars(bob).values()) print(only_values) # 👉️ [1, 'bobbyhadz', 100]

The vars function takes an object and returns the __dict__ attribute of the given module, class, instance or any other object that has a __dict__ attribute.

The vars() function raises a TypeError if the provided object doesn't have a __dict__ attribute.

Which approach you pick is a matter of personal preference. I'd use the __dict__ attribute directly to be more explicit.

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.