Python delattr()

In this post, we will see about Python delattr() method.
Python delattr() method deletes the named attribute if present in the object.


Syntax

As you can see it takes three arguments
object: It is name of the class of which you want to remove the attribute
name: It is the name of attribute
delattr(object, name) is eqvivalent to :


Example

Let’s understand with the help of example.

class Customer: name = 'Martin' age = 30 customer = Customer() print("Name of customer:",getattr(customer,'name')) print("Age of customer:",getattr(customer,'age')) #Let's delete age attribute delattr(Customer,'age') #Let's try to print it after deleting and it will raise AttributeError print("Age of customer:",getattr(customer,'age'))

Output:

Name of customer: Martin
Age of customer: 30
—————————————————————————
AttributeError Traceback (most recent call last)
in ()
10 delattr(Customer,’age’)
11 #Let’s try to print it after deleting
—> 12 print(“Age of customer:”,getattr(customer,’age’))

AttributeError: ‘Customer’ object has no attribute ‘age’

As you can see delattr deleted the attribute from the class.
That’s all about Python delattr() function.

Leave a Reply

Your email address will not be published. Required fields are marked *