What is the use of the "delattr" method in Python?

The **delattr** method in Python is used to delete an attribute from an object. It is used when you want to remove an attribute from an object dynamically, for instance, to clean up an object or to remove an attribute that is no longer needed. The method takes two arguments: the first argument is the object on which the attribute is to be deleted and the second argument is the name of the attribute to be deleted.

Here is an example of using **delattr**:

class MyClass:
    def __init__(self):
        self.x = 10

obj = MyClass()
print(obj.x) # 10

delattr(obj, 'x')
    print(obj.x) # AttributeError: 'MyClass' object has no attribute 'x'
except AttributeError:
    print("AttributeError: 'MyClass' object has no attribute 'x'")

In this example, we have a class **MyClass** with an attribute **x**. After creating an instance of the class, we print the value of **x**. Then, we use **delattr** to delete the attribute **x** from the instance **obj**. Attempting to access the deleted attribute will result in an **AttributeError**.

Related Questions You Might Be Interested