Python delattr Function with Examples - Python Tutorial | Logic Practice
Python Course / Other / Python delattr Function with Examples

Python delattr Function with Examples

BLUF: This lesson on Python delattr Function with Examples provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Python delattr Function with Examples

Mastering Python delattr Function with Examples is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

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 = "[email protected]"

    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 = "[email protected]"

# 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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience