delattr() in Python
The delattr() method is used to delete the named attribute from the object, with the prior permission of the object.
Syntax:
delattr(object, name): The function takes only two parameter:
- object: from which the name attribute is to be removed.
- name: of the attribute which is to be removed.
Return: The function doesn’t return any value.
The Working : Suppose we have a class by named Geek, and it has five students as the attribute. So, using the delattr() method, we can remove any one of the attributes.
Python3
class Geek: domain = "w3wiki.org" if __name__ = = '__main__' : geeks = Geek() print ( "Before deleting domain attribute from geeks object:" ) print (geeks.domain) delattr (geeks, "domain" ) print ( "After deleting domain attribute from geeks object:" ) # this will raise AttributeError if we try to access 'domain' attribute print (geeks.domain) |
Output:
Traceback (most recent call last): File "02d61301-4399-4354-b3c3-86641ba21460.py", line 9, in <module> delattr(geeks, "domain") AttributeError: domain
Explanation: The object of the class Geek is having one attribute named domain. If we use delattr() function on the geeks object of the Geeks class for the domain attribute, then it’ll no more have the attribute domain. In that case, if we want to access the domain attribute, it will raise an AttributeError.
delattr() and del() in Python
In this article, we are going to see delattr() and del() functions in Python