Python delattr Function with Examples

The delattr function in Python serves the purpose of removing an attribute from a class. It requires two arguments: the first being an instance of the class, and the second being the name of the attribute intended for deletion. Once the attribute has been removed, it will no longer exist within the class, and attempting to access it through the class object will result in an error.

Python delattr Function Syntax

It has the following syntax:

Example

delattr (object, name)

Parameters

  • object : Object of the class which contains the attribute.
  • name : The name of the attribute to delete. It must be a string.
  • Return

It returns a complex number.

Different Examples for Python delattr Function

Let’s explore various instances of the delattr function to comprehend its capabilities.

Python delattr Function Example 1

This is a straightforward example featuring a Student class. In this instance, we will utilize the delattr function to remove its email attribute.

Example

# Python delattr() function example

class Student:

    id = 101

    name = "Abdul"

    email = "rohan@abc.com"

    def getinfo(self):

        print(self.id, self.name, self.email)

s = Student()

s.getinfo()

delattr(Student,'email') # Removing attribute

s.getinfo() # error: no attribute 'email' is available

Output:

Output

AttributeError: 'Student' object has no attribute 'email'

101 Rohan[email protected]

Python delattr Function Example 2

An error is raised when an attempt is made to remove an attribute that is not present.

Example

# Python delattr() function example

class Student:

    id = 101

    name = "Abdul"

    email = "rohan@abc.com"

# Declaring function

    def getinfo(self):

        print(self.id, self.name, self.email)

s = Student()

s.getinfo()

delattr(Student,'course') # Removing attribute which is not available

s.getinfo() # error: throws an error

Output:

Output

AttributeError: course

Input Required

This code uses input(). Please provide values below: