Get All Object Attributes in Python

Introduction

In Python, everything is an object - from integers and strings to classes and functions. This may seem odd, especially for primitive types like numbers, but even those have attributes, like real and imag. Each object has its own attributes, which are basically juset properties or characteristics that help define the object.

In this Byte, we will explore different ways to get all attributes of an object in Python, and how to display and manipulate them effectively.

Viewing Object Attributes

To start with, let's look at how we can view the attributes of an object in Python. Python provides a built-in function, dir(), which returns a list of all attributes and methods of an object, which also includes those inherited from its class or parent classes.

Consider a simple class, Company, with a few attributes:

class Company:
    def __init__(self, name, industry, num_employees):
        self.name = name
        self.industry = industry
        self.num_employees = num_employees

Now, let's create an instance of Company and use dir() to get its attributes:

c = Company('Dunder Mifflin', 'paper', 15)
print(dir(c))

This will output:

['__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__', 'industry', 'num_employees', 'name']

As you can see, dir() returns not only the attributes we defined (i.e. name, industry, num_employees), but also a list of special methods (also known as dunder methods) inherent to all Python objects.

Getting their Values

Now that we know how to get the attributes of an object, let's see how to also extract their values. Python provides a built-in function, getattr(), which allows us to get the value of a specific attribute.

Here's how you can use getattr():

name = getattr(c, 'name')
print(name)

This will output:

Dunder Mifflin

In this example, getattr() returns the value of the name attribute of the Company instance c. If the attribute does not exist, getattr() will raise an AttributeError. However, you can provide a third argument to getattr(), which will be returned if the attribute is not found, thus avoiding the error:

location = getattr(c, 'location', 'Not available')
print(location)
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

This will output:

Not available

In this case, since location is not an attribute of c, getattr() returns the provided default value, 'Not available'.

Using __dict__ to get Properties and Values

In Python, every object is equipped with a __dict__ attribute. This built-in attribute is a dictionary that maps the object's attributes to their respective values. This can be very handy when we want to extract all properties and values of an object. Let's see how it works.

class TestClass:
    def __init__(self):
        self.attr1 = 'Hello'
        self.attr2 = 'World'
        
instance = TestClass()
print(instance.__dict__)

When you run the above code, it will output:

{'attr1': 'Hello', 'attr2': 'World'}

Note: __dict__ does not return methods of an object, only the properties and their values.

Formatting Object Attributes into Strings

Sometimes you may want to format the attributes of an object into a readable string for display or logging purposes. Python's built-in str function can be overridden in your class to achieve this. Here's how you can do it:

class TestClass:
    def __init__(self):
        self.attr1 = 'Hello'
        self.attr2 = 'World'

    def __str__(self):
        return str(self.__dict__)
        
instance = TestClass()
print(str(instance))

When you run the above code, it will output:

"{'attr1': 'Hello', 'attr2': 'World'}"

Employing vars() for Attribute Extraction

Another way to extract attributes from an object in Python is by using the built-in vars() function. This function behaves very similar to the __dict__ attribute and returns the __dict__ attribute of an object. Here's an example:

class TestClass:
    def __init__(self):
        self.attr1 = 'Hello'
        self.attr2 = 'World'
        
instance = TestClass()
print(vars(instance))

When you run the above code, it will output:

{'attr1': 'Hello', 'attr2': 'World'}

Note: Like __dict__, vars() also does not return methods of an object, only the properties and their values.

Conclusion

Getting all of the attributes of an object in Python can be achieved in several ways. Whether you're using dir(), the __dict__ attribute, overriding the str function, or using the vars() function, Python provides a variety of tools to extract and manipulate object attributes.

Last Updated: August 24th, 2023
Was this helpful?

Ā© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms