Python delattr() function
The delattr() function in Python is used to delete the named attribute from the object, with the prior permission of the object.
Syntax
1 2 3 |
delattr(object, name) |
Parameter
object : This parameter represents the object from which the name attribute which is to be removed.
name : This parameter represents the name attribute which is to be removed.
Return
The function doesn’t return any value, it just removes the attribute, only if the object allows it.
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# Python Program explaining # delattr() function class Name: stu1 = "Reema" stu2 = "Varun" stu3 = "Sukla" stu4 = "Shivam" stu5 = "Amar" name = Name() print('Names before delattr()--') print('First Rank= ',name.stu1) print('Second Rank= ',name.stu2) print('Third Rank= ',name.stu3) print('Fourth Rank= ',name.stu4) # implementing the method delattr(Name, 'stu4') print('After deleting fourth name:') print('First = ',name.stu1) print('Second = ',name.stu2) print('Third = ',name.stu3) #when the fourth attribute is called, the compiler raises an error: print('Raising an error:\n') print('Fourth = ',name.stu4) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Names before delattr()-- First Rank= Reema Second Rank= Varun Third Rank= Sukla Fourth Rank= Shivam After deleting fourth name: First = Reema Second = Varun Third = Sukla Raising an error: Traceback (most recent call last): File "main.py", line 28, in <module> print('Fourth = ',name.stu4) AttributeError: 'Name' object has no attribute 'stu4' |