What is the purpose of the __dict__ attribute in Python?

Python >   Python Classes and Objects >   Python Introduction to OOP  

Long Question

253


Answer:

In Python, the __dict__ attribute is a special attribute that contains the namespace of an object. It is a dictionary-like object that maps attribute names to their corresponding values.

Whenever you create a new instance of a class, Python creates a new namespace to store the instance's attributes. The __dict__ attribute provides a way to access this namespace directly, and to manipulate the attributes of an instance dynamically.

Here's an example to illustrate the use of __dict__:


class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 30)

# Accessing the namespace with __dict__
print(p.__dict__)   # {'name': 'Alice', 'age': 30}

# Adding a new attribute dynamically
p.city = "New York"
print(p.__dict__)   # {'name': 'Alice', 'age': 30, 'city': 'New York'}

# Removing an attribute dynamically
del p.age
print(p.__dict__)   # {'name': 'Alice', 'city': 'New York'}

In this example, we define a Person class with two attributes (name and age). When we create a new instance of the class (p), Python creates a new namespace to store the instance's attributes. We can access this namespace directly using the __dict__ attribute, and we can manipulate the attributes dynamically by adding or removing items from the dictionary.

In summary, the __dict__ attribute in Python is a special attribute that contains the namespace of an object. It provides a way to access and manipulate an object's attributes dynamically, which can be useful in a variety of situations.


This Particular section is dedicated to Question & Answer only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.