Delete Properties of Class Object in Python

Delete Properties of Class Objects

We can delete the property of a class object in Python using del keyword. Write an expression with del keyboard followed by the reference to the property in object.

For example, if object1 is a class object in Python, then to delete its property property1, use the following syntax.

del object1.property1

You may need to replace object1 with your class object name and property1 with the property name which you would like to delete from the class object.

Example

Let us take an example scenario where we have a class named Person with two properties: name, age.

We create an object person1 of type Person, with some initial values for its properties: Person('Mike', 22) and print the details of this class object calling printDetails() function.

Then, we shall delete the property age for the person1 object using del keyword, and try to call printDetails() function on the person1 object.

Python Program

class Person:
    def __init__(self, name="NA", age="0"):
        self.name = name
        self.age = age

    def printDetails(self):
        print("Person Details")
        print("Name :", self.name)
        print("Age  :", self.age, end="\n\n")

person1 = Person("Mike", 22)
person1.printDetails()

# For some reason we delete age property
del person1.age
person1.printDetails()
Run Code Copy

Output

Person Details
Name : Mike
Age  : 22

Person Details
Name : Mike
Traceback (most recent call last):
  File "/Users/arjun/Desktop/flask_app/main.py", line 16, in <module>
    person1.printDetails()
  File "/Users/arjun/Desktop/flask_app/main.py", line 9, in printDetails
    print("Age  :", self.age, end="\n\n")
AttributeError: 'Person' object has no attribute 'age'

When we printed out the person details for the first time we have the age property in the object. But when we tried to print the details of the person object the second time, we have already deleted the age property. Therefore, trying to access the property which is not present in the object raised AttributeError.

Summary

In this Python Classes and Objects tutorial, we learned how to delete properties of a class object.

Related Tutorials

Code copied to clipboard successfully 👍