What is the delattr() function in Python?

The delattr() function in Python is used to delete an attribute from an object.

Syntax

The delattr() function can be declared as shown in the code snippet below.

delattr(obj, attr)
  • obj: The object from which the attribute attr will be deleted.
  • attr: The attribute that will be deleted from the object obj.

Return value

The delattr() function does not return any value. It simply removes the attribute from the object if the operation is successful.

Example

Consider the code snippet below which demonstrates the use of the delattr() function.

class Class1:
attr1 = "attribute1"
attr2 = "attribute2"
attr3 = "attribute3"
obj1 = Class1
try:
print('attr2: ' + obj1.attr2)
delattr(obj1, 'attr2')
print('attr2: ' + obj1.attr2)
except AttributeError:
print("Attribute not found!!")

Explanation

A class, Class1, is declared in lines 1-4. obj1 is an instance declared of Class1. The delattr() function is used in line 10 to delete the attribute attr2 of obj1. After deleting attr2 from obj1, trying to access attr2 returns the AttributeError.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources