Cover Image for __dict__ in Python
129 views

__dict__ in Python

The Python __dict__ is a special attribute of an object or a class that represents a dictionary containing the object’s or class’s attributes (variables and methods). The keys of this dictionary are the names of the attributes, and the values are the corresponding attribute values (including methods, which are also objects in Python).

Here are two common uses of __dict__:

  1. Object’s __dict__: When you access the __dict__ attribute of an instance object, you get a dictionary containing the object’s instance variables and their values. This can be useful for introspection and dynamic attribute manipulation:
Python
 class MyClass:
   def __init__(self, x, y):
       self.x = x
       self.y = y

 obj = MyClass(1, 2)
 print(obj.__dict__)  # Output: {'x': 1, 'y': 2}

In this example, obj.__dict__ contains the attribute names (‘x’ and ‘y’) as keys and their corresponding values.

  1. Class’s __dict__: When you access the __dict__ attribute of a class, you get a dictionary containing the class’s namespace, which includes class-level variables and methods:
Python
 class MyClass:
   class_variable = 10

   def __init__(self, x):
       self.x = x

   def my_method(self):
       pass

 print(MyClass.__dict__)

The output will include class-level attributes, instance methods, and other attributes related to the class:

Python
{
    '__module__': '__main__',
    'class_variable': 10,
    '__init__': <function MyClass.__init__ at 0x...>,
    'my_method': <function MyClass.my_method at 0x...>,
    # ... other attributes and methods
}

Note that the __dict__ of a class contains various attributes, including the class-level attributes and methods, as well as internal attributes used by Python (e.g., '__module__').

While __dict__ can be useful for introspection and dynamic attribute manipulation, it’s generally not recommended to directly manipulate or modify the __dict__ attribute of objects or classes in production code unless you have a specific use case that requires it. Python provides more controlled and standard ways to work with attributes and classes, such as using built-in functions like setattr(), getattr(), and class decorators.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS