The delattr() function is a built-in function in Python that deletes the named attribute from the specified object. It takes two arguments: the object and the name of the attribute to be deleted. If the specified attribute does not exist, it raises an AttributeError.
Parameter Values
| Parameter | Description |
|---|---|
| object | The object from which the attribute will be deleted. |
| name | A |
Return Values
The delattr() function has no return value; it returns None.
How to Use delattr() in Python
Example 1:
The delattr() function in Python is used to delete an attribute from an object.
class Example:
def __init__(self):
self.attr = 10
obj = Example()
delattr(obj, 'attr')
# Attribute 'attr' is deleted from the object
Example 2:
If the specified attribute does not exist, delattr() raises an AttributeError.
class Example:
def __init__(self):
self.attr = 10
obj = Example()
delattr(obj, 'non_existent_attr')
# Raises AttributeError: non_existent_attr
Example 3:
The delattr() method can also be used with built-in objects.
m = {'a': 1, 'b': 2}
delattr(m, 'a')
# Key 'a' is deleted from the dictionary