Python Tutorial
Deleting Attributes and Objects in Python
How to Delete Attributes and Objects in Python?
Following methods or functions can be used for deleting Python attributes and objects:
delattr function in Python
With the object's permission, the delattr() method is used to delete the named attribute from the object.
Syntax:
delattr(object, name)
There are just two parameters in this function:
-
object: from which the name attribute is to be removed.
-
name: of the attribute which is to be removed.
The function does not return a value; instead, it just removes the attribute if the object permits it.
Example:
# Python code to illustrate delattr()
class WSC:
stu1 = "Harshal"
stu2 = "Zishan"
stu3 = "Sumit"
stu4 = "Amit"
stu5 = "Shravan"
names = WSC()
print('Students before delattr()--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
print('Fifth = ',names.stu5)
# implementing the method
delattr(WSC, 'stu5')
print('After deleting fifth student--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
# this statement raises an error
print('Fifth = ',names.stu5)
Output:
Students before delattr()--
First = Harshal
Second = Zishan
Third = Sumit
Fourth = Amit
Fifth = Shravan
After deleting fifth student--
First = Harshal
Second = Zishan
Third = Sumit
Fourth = Amit
del operator in Python
In Python, there is one more operator that performs the same function as the delattr() method. It's the del command.
Example:
# Python code to illustrate del()
class WSC:
stu1 = "Harshal"
stu2 = "Zishan"
stu3 = "Sumit"
stu4 = "Amit"
stu5 = "Shravan"
names = WSC()
print('Students before del--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
print('Fifth = ',names.stu5)
# implementing the operator
del WSC.stu5
print('After deleting fifth student--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
# this statement raises an error
print('Fifth = ',names.stu5)
Output:
Students before del--
First = Harshal
Second = Zishan
Third = Sumit
Fourth = Amit
Fifth = Shravan
After deleting fifth student--
First = Harshal
Second = Zishan
Third = Sumit
Fourth = Amit
The output is the same with an error:
Traceback (most recent call last):
File "/home/7c239eef9b897e964108c701f1f94c8a.py", line 26, in
print('Fifth = ',names.stu5)
AttributeError: 'WSC' object has no attribute 'stu5'
QUIZ!
