
__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__
:
- 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:
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.
- 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:
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:
{
'__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.