delattr(object, attribute) Removes the attribute of the input object
object (required ) , input object for which the attribute will be removed.
attribute ( required ), attribute to be removed.
Read more on Class Object and Attributes
Deleting an instance attribute
class Animal():
#class attributes
species='carnivores'
#instance attributes
def __init__(self1,name1,age):
self1.name= name1
self1.age=age
tiger=Animal("Ronald",5) # object created
print(tiger.age) # 5
delattr(tiger,'age')
#print(tiger.age) # Error
In above code we created an object tiger. By using delattr()
we removed one attribute age. The last line ( commented ) will generate error as we already removed the attribute age before using it.
AttributeError: 'Animal' object has no attribute 'age'
Deleting attribute of particular object.
We will create two objects and check that the delattr()
will only delete for the input object only. Here in last line we can print the age of the other object lion.
tiger=Animal("Ronald",5)
lion=Animal('Alex',6)
print(tiger.age) # 5
delattr(tiger,'age')
print(lion.age) # 6
Deleting class attribute
Once the class attribute is removed, it is not available to all objects.
tiger=Animal("Ronald",5)
lion=Animal('Alex',6)
print(tiger.species)
delattr(Animal,'species')
#print(tiger.species)
#print(lion.species)
Both the objects tiger and lion can't access the class attribute.
AttributeError: 'Animal' object has no attribute 'species'
Using del operator
tiger=Animal("Ronald",5) # object created
print(tiger.age) # 5
del tiger.age
print(tiger.age) # Error
The last line will generate error as we have deleted the attribute before this line.
«All Built in Functions in Python setattr() getattr() hasattr()
← Subscribe to our YouTube Channel here