delattr() and del() in Python

PythonServer Side ProgrammingProgramming

These two functions are used to remove attributes from classes. The delattr() allows dynamoc deletion of attribute while the del() is more efficient explicit in deleting the attribute.

Using delattr()

Syntax: delattr(object_name, attribute_name)
Where object name is the name of the object, instantiated form the class.
Attribute_name is the name of the attribute to be deleted.

Example

In the below example we consider a class named custclass. It has the id of the customers as its attributes. Next we instantiate the class as an object named customer and print its attriutes.

class custclass:
   custid1 = 0
   custid2 = 1
   custid3 = 2
customer=custclass()
print(customer.custid1)
print(customer.custid2)
print(customer.custid3)

Output

Running the above code gives us the following result −

0
1
2

Example

In the next step we again run the program by applying the delattr() function. This time when we want to print the id3, we get an error as the attribute is removed from the class.

class custclass:
   custid1 = 0
   custid2 = 1
   custid3 = 2
customer=custclass()
print(customer.custid1)
print(customer.custid2)
delattr(custclass,'custid3')
print(customer.custid3)

Output

Running the above code gives us the following result −

0
Traceback (most recent call last):
1
File "xxx.py", line 13, in print(customer.custid3)
AttributeError: 'custclass' object has no attribute 'custid3'

Using del()

Syntax: del(object_name.attribute_name)
Where object name is the name of the object, instantiated form the class.
Attribute_name is the name of the attribute to be deleted.

Example

We repeat the above example with del() function. Please note there is a difference in syntax from delattr()

class custclass:
   custid1 = 0
   custid2 = 1
   custid3 = 2
customer=custclass()
print(customer.custid1)
print(customer.custid2)
del(custclass.custid3)
print(customer.custid3)

Output

Running the above code gives us the following result −

0
1
Traceback (most recent call last):
File "xxx.py", line 13, in
print(customer.custid3)
AttributeError: 'custclass' object has no attribute 'custid3'
raja
Published on 07-Aug-2019 11:52:01
Advertisements