Python __dict__
In Python, __dict__
is a built-in attribute of an object or class that returns a dictionary containing the attributes and their values of the object or class.
For an object, __dict__
represents the instance's namespace, i.e., a dictionary containing all the instance variable names as keys and their corresponding values as values.
For a class, __dict__
represents the class's namespace, i.e., a dictionary containing all the class variable names as keys and their corresponding values as values.
Here is an example to demonstrate the usage of __dict__
:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John Doe", 25)
print(person.__dict__) # Output: {'name': 'John Doe', 'age': 25}
person.__dict__["gender"] = "Male"
print(person.__dict__) # Output: {'name': 'John Doe', 'age': 25, 'gender': 'Male'}
print(Person.__dict__) # Output: {'__module__': '__main__', '__init__': <function Person.__init__ at 0x7f91900e4950>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
In the above example, person.__dict__
returns a dictionary containing the attributes and values of the person
object. Similarly, Person.__dict__
returns a dictionary containing the attributes and values of the Person
class.