Summary: In this programming example, we will learn two different ways to delete properties of a user-defined object in Python.
Method 1: Using del
The del
statement can easily delete a property of a Python object. For example, in the following code, we are deleting the department
property of the Student
object using the same.
class Student:
def __init__(self, name, department):
self.name = name
self.department = department
obj = Student("Bicky Newton", "IT")
del obj.department #deletes department property
Method 2: Using delattr()
The delattr()
is an inbuilt method in Python that deletes the attribute (property) of the specified object.
Syntax:
delattr(obj, attribute)
Example:
class Student:
def __init__(self, name, department):
self.name = name
self.department = department
obj = Student("Bicky Newton", "IT")
delattr(obj, department) #deletes department property
These are the two methods using which we can delete the properties of a user-defined object in Python.