In Python delete attribute, you can delete an attribute from an object using the del
statement or the delattr()
function. Here’s how you can use each method:
- Using the
del
statement:
Thedel
statement allows you to delete an attribute from an object by specifying the object name followed by the attribute name.
class MyClass: def __init__(self): self.attribute = 10 obj = MyClass() # Delete the 'attribute' attribute using the 'del' statement del obj.attribute # Check if 'attribute' is present in obj if hasattr(obj, 'attribute'): print("Attribute 'attribute' is present.") else: print("Attribute 'attribute' is not present.")
Output:
Attribute 'attribute' is not present.
- Using the
delattr()
function:
Thedelattr()
function takes two arguments: the object from which you want to delete the attribute and the name of the attribute you want to delete.
class MyClass: def __init__(self): self.attribute = 10 obj = MyClass() # Delete the 'attribute' attribute using the 'delattr()' function delattr(obj, 'attribute') # Check if 'attribute' is present in obj if hasattr(obj, 'attribute'): print("Attribute 'attribute' is present.") else: print("Attribute 'attribute' is not present.")
Output:
Attribute 'attribute' is not present.
Both the del
statement and the delattr()
function can be used to delete an attribute from an object. Choose the method that suits your needs and coding style.