What is delattr() in Python?
delattr() is a Python method that is used for removing an attribute from an object (provided that the object allows it).
Syntax
delattr() can be called as:
delattr(object, name)
Parameters
The delattr() method takes the following parameters:
object: This is the object whose (desired) attribute should be removed.name: This is a string that specifies the attribute that needs to be removed.
Return value
It must be noted that there is no value returned by the delattr() method. It returns None, as its job is merely getting rid of the desired attribute.
Code example
class marks:Eng = 40Urdu = 55Math = 60Marks = marks()print('a = ',Marks.Eng)print('b = ',Marks.Urdu)print('c = ',Marks.Math)delattr(marks, 'Math')print('--After deleting Math attribute--')print('a = ',Marks.Eng)print('b = ',Marks.Urdu)# Raises Errorprint('c = ',Marks.Math)
Code explanation
-
Lines 1–4: We define a
marksclass. -
Line 6: We create the object of the
marksclass. -
Lines 8–10: We print the attributes of the
marksclass. -
Line 12: We delete the
Mathattribute from themarksclass, usingdelattr(marks, 'Math'). -
Lines 15–16: We print the attributes of the
marksclass again. -
Line 19: We are shown an error, because the
Mathattribute has been removed from the class and we cannot display it.
Conclusion
The delattr() method is useful for removing certain attribute(s) of an object.
Free Resources