How python setattr() and delattr() function works?

Python delattr() Function

Python delattr() function is used to delete an attribute from a class. It takes two parameters, first is an object of the class and second is an attribute which we want to delete. After deleting the attribute, it no longer available in the class and throws an error if try to call it using the class object.

Python delattr() Function Example

class Student:  
    id = 101  
    name = "Pranshu"  
    email = "pranshu@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:

101 Pranshu pranshu@abc.com
AttributeError: course

Python setattr() Function

Python setattr() function is used to set a value to the object’s attribute. It takes three arguments, i.e., an object, a string, and an arbitrary value, and returns none. It is helpful when we want to add a new attribute to an object and set a value to it.

Python setattr() Function Example

class Student:  
    id = 0  
    name = ""  
      
    def __init__(self, id, name):  
        self.id = id  
        self.name = name  
          
student = Student(102,"Sohan")  
print(student.id)  
print(student.name)  
#print(student.email) product error  
setattr(student, 'email','sohan@abc.com') # adding new attribute  
print(student.email)  

Output:

102
Sohan
sohan@abc.com