Python delattr() function is an eraser for attributes (variables or methods) attached to an object or class. It lets you dynamically remove those attributes during your program’s execution, giving you more control over the structure of your objects and classes.
delattr()
Syntax
delattr(object, attribute_name)
delattr()
: The built-in Python function responsible for removing attributes.object
: The object or class from which you want to delete an attribute.attribute_name
: The name of the attribute you want to remove, provided as a string.
Example 1: Python delattr()
class MyClass:
def __init__(self):
self.my_attribute = "Hello"
obj = MyClass()
print(obj.my_attribute) # Output: Hello
delattr(obj, 'my_attribute')
try:
print(obj.my_attribute) # Raises AttributeError
except AttributeError:
print("Attribute 'my_attribute' has been deleted")
Code Explanation
- Line 1: Defines a class with an attribute
my_attribute
. - Line 5: Creates an instance of
MyClass
. - Line 6: Prints the initial value of the attribute.
- Line 8: Deletes the
my_attribute
from theobj
instance. - Line 10: Attempts to access the deleted attribute and handles the expected error.
- Line 11: Prints a message indicating the attribute has been deleted.
Example 2: Deleting Attribute Using del
Operator
class MyClass:
def __init__(self):
self.my_attribute = "Hello"
obj = MyClass()
del obj.my_attribute # Deletes the attribute using 'del'
try:
print(obj.my_attribute) # Raises AttributeError
except AttributeError:
print("Attribute 'my_attribute' has been deleted")
Example provides an alternative way to delete an attribute using the operator directly.