In Python, the delattr() function is used to delete an object's attribute. It takes two parameters: the first is the object from which to delete the attribute, and the second is the name of the attribute to delete. If the specified attribute doesn't exist in the object, it will raise an AttributeError exception.
delattr() Function Usage Examples
Here are examples of using the delattr() function to delete object attributes:
class MyClass:
x = 1
y = 2
obj = MyClass()
print(obj.x) # Output: 1
# Use delattr() function to delete object attribute
delattr(obj, 'x')
# Now accessing the deleted attribute will raise AttributeError
# print(obj.x) # Raises AttributeError
# Deleting non-existent attribute raises AttributeError
# delattr(obj, 'z') # Raises AttributeError
In this example, we created a class MyClass with attributes x and y. Then we created an instance obj of MyClass and used the delattr() function to delete attribute x from obj.
Attempting to access the deleted attribute x afterwards will raise an AttributeError exception. Note that trying to delete a non-existent attribute will also raise an AttributeError exception.