Course contentsShow
← Python
Lesson 429 of 1,0607. Object-Oriented ProgrammingFree lesson

Inspecting Attributes via Internal Dictionaries

Learners will navigate the __dict__ attribute of objects and classes to dynamically inspect and manipulate internal data storage at runtime.

In this lesson, you will learn how to peek under the hood of your Python objects by accessing their internal storage dictionary, known as __dict__.

The Magic of __dict__

Every time you create an object in Python, the interpreter maintains a secret dictionary that stores the object's instance variables and their current values. This dictionary is accessible via the special __dict__ attribute. Think of __dict__ as a "behind-the-scenes" map where Python looks up attribute names to find their associated data.

Because this is a standard Python dictionary, you can use it to inspect an object's state dynamically, or even add and remove attributes while your program is running.

Inspecting Internal State

Imagine you have a simple class modeling a Robot:

class Robot:
    def __init__(self, name, battery):
        self.name = name
        self.battery = battery

my_robot = Robot("R2D2", 100)

# Inspect the object's internal dictionary
print(my_robot.__dict__)
# Output: {'name': 'R2D2', 'battery': 100}

# You can even modify attributes directly through the dictionary!
my_robot.__dict__['battery'] = 50
print(my_robot.battery)
# Output: 50

Why Use This?

Accessing __dict__ is incredibly powerful for debugging or creating flexible systems where you don't know the attribute names ahead of time. Instead of guessing what variables an object might have, you can simply iterate over its __dict__ keys.

Note that __dict__ only tracks instance attributes. If you want to see class attributes—variables shared by all instances—you would look at the __dict__ of the class itself, rather than the object instance.

By manipulating the __dict__, you are interacting directly with the object's memory storage, allowing for a level of dynamism that standard dot-notation (object.attribute) doesn't provide. Just remember that with great power comes the responsibility to keep your object's state consistent!

Key Takeaway: The __dict__ attribute provides a direct window into an object's instance variable storage, allowing you to dynamically inspect and modify data at runtime.