Python delattr() Method

The delattr() method deletes the named attribute from the object if the object allows it.

Syntax:

delattr(object, name)

Parameters:

  1. object: The object from which the attribute is to be deleted.
  2. Name: An attribute name to be deleted as string.

Return Value:

None.

The following example deletes attributes from the given object.

Example: delattr()
class student:
    name = 'John'
    age = 25

print(dir(student))

delattr(student, 'age')

print("After the delattr() method is called:")
print(dir(student))
Output
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
'__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']
After the delattr() method is called:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 
'name']

Above, the dir(student) output contains age in the list, but after calling delattr(student, 'age'), it deletes the age attribute and so does not exist in the list.

Alternatively, the del keyword can be used to delete the attribute instead of the delattr() method.

Example: del Keyword
class student:
    name = 'John'
    age = 25

del student.age
print(dir(student))
Output
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 
'name']