Python delattr()
is a built-in function that deletes the named attribute of an object. delattr()
does not return any value and deletes the attribute if object allows it.
delattr(object,name)
As you can see in above syntax, Python delattr()
takes two arguments:
As we already mentioned delattr()
doesn’t return any value, instead, it only deletes the mentioned attribute from the object provided that the object allows it.
delattr()
is compatible with both versions Python 2.x and 3.x.
Let’s just create a simple class and its object to demonstrate how delattr()
works.
class Example:
def __init__(self,a):
self.a = a
#creating an object
obj = Example(5)
print(obj.a)
#Now removing attribute x
delattr(obj,'a')
print(obj.a)
Output
This will generate following output.
5 Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> print(obj.a) AttributeError: 'Example' object has no attribute 'a'
Explanation
As you can see clearly, delattr(obj, 'a')
, removed attribute a
from object obj
. Hence it throws AttributeError
when we try to access that removed attribute.