Python delattr() Function

The delattr() function in Python is used when we need to delete an attribute from a specified object. For example:

class fresherearth:
    ID = 1249
    Name = "Kenneth"
    Designation = "Java Content Manager"
    Country = "Canada"

delattr(fresherearth, "Designation")

Using the following statement in above program:

delattr(fresherearth, "Designation")

The attribute named Designation will no longer be available for the class fresherearth, because it gets deleted using the delattr() function.

Python delattr() Function Syntax

The syntax of delattr() function in Python is:

delattr(object, attribute)

The object refers to the object from where the specified attribute has to be delete. The attribute must be enclosed within single or double quote.

Note: Both parameters are required.

Python delattr() Function Example

Here is the modified version of the program that was given at start of this article. With this program, before using the delattr() function to delete a particular attribute from the object, I've printed the value of that attribute:

class fresherearth:
    ID = 1249
    Name = "Kenneth"
    Designation = "Java Content Manager"
    Country = "Canada"

ob = fresherearth()
print("Designation =", ob.Designation)

delattr(fresherearth, "Designation")

The output would be:

Designation = Java Content Manager

But if you will try to execute the same statement, that is:

print("Designation =", ob.Designation)

after deleting the attribute Designation. Then here is the error, you'll see:

python delattr function

The exception raised is AttributeError, therefore if you're trying to delete an attribute using the delattr() function, that doesn't exist in specified object. Then in that case too, this exception will get raised. Therefore be sure to handle this exception. Let's create a program to handle this exception while deleting and printing any attribute of the class fresherearth:

class fresherearth:
    ID = 1249
    Name = "Kenneth"
    Designation = "Java Content Manager"
    Country = "Canada"

ob = fresherearth()

try:
    print("\nDesignation =", ob.Designation)
except AttributeError:
    print("\nThis attribute is not available.")

try:
    delattr(fresherearth, "Designation")
except AttributeError:
    print("\nThe specified attribute does not exist in the specified object.")

try:
    print("\nDesignation =", ob.Designation)
except AttributeError:
    print("\nThis attribute is not available.")

The sample output is shown in the snapshot given below:

python delattr function example

Python Online Test


« Previous Function Next Function »