- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
delattr() and del() in Python
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'