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 = ""  
# Declaring function  
    def getinfo(self):  
s = Student()  
delattr(Student,'course') # Removing attribute which is not available  
s.getinfo() # error: throws an error  


101 Pranshu
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):  = id  = name  
student = Student(102,"Sohan")  
#print( product error  
setattr(student, 'email','') # adding new attribute