The delattr function in Python serves the purpose of removing an attribute from a class. It requires two arguments: the first being an instance of the class, and the second being the name of the attribute intended for deletion. Once the attribute has been removed, it will no longer exist within the class, and attempting to access it through the class object will result in an error.
Python delattr Function Syntax
It has the following syntax:
delattr (object, name)
Parameters
- object : Object of the class which contains the attribute.
- name : The name of the attribute to delete. It must be a string.
Return
It returns a complex number.
Different Examples for Python delattr Function
Let’s explore various instances of the delattr function to comprehend its capabilities.
Python delattr Function Example 1
This is a straightforward example featuring a Student class. In this instance, we will utilize the delattr function to remove its email attribute.
# Python delattr() function example
class Student:
id = 101
name = "Abdul"
email = "rohan@abc.com"
def getinfo(self):
print(self.id, self.name, self.email)
s = Student()
s.getinfo()
delattr(Student,'email') # Removing attribute
s.getinfo() # error: no attribute 'email' is available
Output:
AttributeError: 'Student' object has no attribute 'email'
101 Rohan[email protected]
Python delattr Function Example 2
An error is raised when an attempt is made to remove an attribute that is not present.
# Python delattr() function example
class Student:
id = 101
name = "Abdul"
email = "rohan@abc.com"
# Declaring function
def getinfo(self):
print(self.id, self.name, self.email)
s = Student()
s.getinfo()
delattr(Student,'course') # Removing attribute which is not available
s.getinfo() # error: throws an error
Output:
AttributeError: course