__dict__ Attribute

Learn how Python's __dict__ attribute exposes an object's attributes as a dictionary.

Loading...
__dict__ Attribute

In Python, the __dict__ attribute provides a dictionary representation of an object's namespace (its attributes and their values).

This is especially useful for introspection and debugging.

Example: Viewing Attributes with __dict__

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model
 
# Create an object
car = Car("Toyota", "Corolla")
 
# Access the __dict__ attribute
print(car.__dict__)
 

Output:

{'brand': 'Toyota', 'model': 'Corolla'}

Here, the __dict__ attribute returns a dictionary of the car object's attributes.

Example: Updating Attributes via __dict__

Since __dict__ is a regular dictionary, modifying it updates the object’s attributes:

car.__dict__['year'] = 2025
print(car.year)  # Output: 2025

Notes:

  • Most user-defined classes have a __dict__, but not all built-in objects do (e.g., int.__dict__ raises an error).
  • Classes themselves also have a __dict__ that stores their methods and class variables.

👉 Next tutorial: Python help() Method

Support my work!