Python delattr() Function with Examples

The delattr() built-in python function is used to delete an attribute from the object when the object allows it. Simply we can say that the....

In this tutorial, we will discuss about the delattr() function in python programming language with the help of examples.

Python delattr() function

Python delattr() function

The built-in python function is used to delete an attribute from the object when the object allows it. Simply we can say that the delattr() function removes the named attribute of an object with prior permission.

Syntax 

delattr(object, name)

Parameters of delattr() function in python 

The function in python takes two arguments or parameters i.e.,

- object from which the named attribute is removed.

- name of the attribute which is to be removed.

Return value of Python delattr() function 

The python delattr() function does not return any value, it returns . It is only used to remove an attribute from the object.

Example 1: How Python delattr() Function works?

class Answersjet:

  stu1 = 'Deepak'

  stu2 = 'Reena'

  stu3 = 'Ekta'

names = Answersjet() 

print('First Student = ',names.stu1)

print('Second Student = ',names.stu2)

print('Third Student = ',names.stu3)

delattr(Answersjet, 'stu3')

print('--After deleting stu3 attribute--')

print('First Student = ',names.stu1)

print('Second Student = ',names.stu2)

# Raises Error

print('Third Student = ',names.stu3)

Output

First Student =  Deepak

Second Student = Reena

Third Student = Ekta

--After deleting stu3 attribute--

First Student = Deepak

Second Student = Reena

Traceback (most recent call last):

File "<string>", line 14, in <module>

AttributeError: 'Answersjet' object has no attribute 'stu3'

Example 2: Deleting Attribute Using del Operator

class Answersjet:

  stu1 = 'Deepak'

  stu2 = 'Reena'

  stu3 = 'Ekta'

names = Answersjet() 

print('First Student = ',names.stu1)

print('Second Student = ',names.stu2)

print('Third Student = ',names.stu3)

# Deleting attribute stu3

del Answersjet.stu3

print('--After deleting stu3 attribute--')

print('First Student = ',names.stu1)

print('Second Student = ',names.stu2)

# Raises Attribute Error

print('Third Student = ',names.stu3)

Output

First Student =  Deepak

Second Student = Reena

Third Student = Ekta

--After deleting stu3 attribute--

First Student = Deepak

Second Student = Reena

Traceback (most recent call last):

File "<string>", line 15, in <module>

AttributeError: 'Answersjet' object has no attribute 'stu3'