How To Print An Object’s Attributes In Python

Hello guys. Welcome back. Today we will learn how to print an object’s attributes in Python. This is a problem that all new and experienced programmers are still searching for a solution. To do it, we tested effectively using the dir() function and the vars() function. Please read to the end of the articles to know how we can do it.

To Print An Object’s Attributes In Python

Using the dir() function

To print out an object’s attributes in Python, you can quickly call the dir() function. This method returns a list of the names in the current local scope and the names of the object’s valid attributes.
You can see other uses of the dir() function in our other posts here.

Code Example

Let’s see the code example below.

class Animals:
    def __init__(self, name, makeSound):
        self.name = name
        self.makeSound = makeSound

# Create an object
animal = Animals("Dog", "Woof")

# Calling the dir() function
print("Print an object's attribute: ", dir(animal))

Output

Using the vars() function

The dir() function print all of the attributes of a Python object. It prints out the list of the names of the object. So you can use the vars() function only to print out the object’s instance attributes and their values.

Let’s see the code example below.

Example

# Import module
from pprint import pprint

class Animals:
    def __init__(self, name, makeSound):
        self.name = name
        self.makeSound = makeSound

# Create an object
animal = Animals("Dog", "Woof")

# Using the vars() to print out an object attributes
print("Print an object's attribute: ", vars(animal))

Output

Print an object's attribute:  {'name': 'Dog', 'makeSound': 'Woof'}

Using the inspect module

The last way is using the inspect module. This module will help inspect certain modules or objects included in the code. You can use the getmember() method to print all attributes of an object in Python.

Example

# Import inspect module
import inspect

class Animals:
    def __init__(self, name, makeSound):
        self.name = name
        self.makeSound = makeSound

# Create an object
animal = Animals("Dog", "Woof")

# Using the getmembers() function of the inspect module
for animal in inspect.getmembers(animal):
    if not animal[0].startswith('_'):
        if not inspect.ismethod(animal[1]):
            print(animal)

Output

('makeSound', 'Woof')
('name', 'Dog')

Summary

Throughout the article, we introduce three methods to print an object’s attributes in Python, but using the vars() function is the easiest way. Leave your comment here if you have any questions about this article.

Thank you for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *