delattr()
is a Python method that is used for removing an attribute from an object (provided that the object allows it).
delattr()
can be called as:
delattr(object, name)
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.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.
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)
Lines 1–4: We define a marks
class.
Line 6: We create the object of the marks
class.
Lines 8–10: We print the attributes of the marks
class.
Line 12: We delete the Math
attribute from the marks
class, using delattr(marks, 'Math')
.
Lines 15–16: We print the attributes of the marks
class again.
Line 19: We are shown an error, because the Math
attribute has been removed from the class and we cannot display it.
The delattr()
method is useful for removing certain attribute(s) of an object.
Free Resources