Python delattr() Function – Tutorial with Examples

The delattr() function in Python is used to delete an attribute from an object. The function takes an object and a string representing the name of the attribute to be deleted, and removes that attribute from the object. If the attribute does not exist, a AttributeError is raised.

Syntax

delattr(object, name)

Parameters

  • object : This is the object from which the attribute is to be deleted.
  • name : This is the string representing the name of the attribute to be deleted.

Return Value

The delattr() function does not return any value. It simply removes the attribute from the object.

Examples

Example 1: Deleting an attribute from an object

# delete an attribute from an object
class Person:
    name = "John"
    age = 30
p = Person()
delattr(p, "age")
print(p.age)

Output.

AttributeError: 'Person' object has no attribute 'age'

Example 2: Deleting an attribute from an instance of a class

# delete an attribute from an instance of a class
class Person:
    name = "John"
    age = 30
p = Person()
del p.age
print(p.age)

Output.

AttributeError: 'Person' object has no attribute 'age'

Example 3: Deleting an attribute from a built-in type

# delete an attribute from a built-in type
d = {'name': 'John', 'age': 30}
del d['age']
print(d)

Output.

{'name': 'John'}

Use Cases

The delattr() function is useful in cases where it is necessary to remove an attribute from an object, such as when cleaning up objects before they are no longer needed. The function is also useful for removing attributes that were dynamically added to objects during the course of a program, or for removing attributes that have become outdated or are no longer needed.

Another use case of delattr() function is when working with classes and instances. If a class has a common attribute across all instances and you want to remove it for a specific instance, delattr() can be used to remove that attribute only for that particular instance, without affecting the other instances or the class itself.

In summary, the delattr() function provides a convenient way to remove attributes from objects in Python, making it an important tool for controlling the behavior and state of objects in a program.

Leave a Reply

Your email address will not be published. Required fields are marked *