Python delattr() Built in Function

The delattr() function in Python is used to delete an attribute from an object. The syntax of the delattr() function is:

delattr(object, attribute_name)

Here are a few examples of using the delattr() function in Python:

Example 1: Delete an attribute from an object

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


# create a Person object
person = Person("Alice", 25)

# delete the 'age' attribute from the Person object
delattr(person, "age")

# print the object's attributes
print(person.__dict__)

In this example, a Person class is defined with two attributes, name and age. An object of this class is created with the name "Alice" and age 25. The delattr() function is then used to delete the age attribute from the person object.

The __dict__ attribute of the person object is then printed to show that the age attribute has been deleted. The output will be:

{'name': 'Alice'}

Example 2: Delete a method from a class 

class MyClass:
    def my_method(self):
        print("Hello, World!")


# delete the 'my_method' method from the MyClass class
delattr(MyClass, "my_method")

# create an object of the MyClass class

obj = MyClass()

# try to call the deleted method
obj.my_method()

In this example, a MyClass class is defined with a my_method() method that prints "Hello, World!". The delattr() function is then used to delete the my_method method from the MyClass class.

An object of the MyClass class is then created, and an attempt is made to call the deleted method using the object. This will raise an AttributeError because the method has been deleted. The output will be:

AttributeError: 'MyClass' object has no attribute 'my_method'

Example 3: Delete a built-in attribute from a module

import math

# delete the 'pi' attribute from the math module

delattr(math, "pi")

# try to access the deleted attribute
print(math.pi)

In this example, the math module is imported, which has a built-in pi attribute. The delattr() function is used to delete the pi attribute from the math module.

An attempt is then made to access the deleted pi attribute using the print() function. This will raise an AttributeError because the attribute has been deleted. The output will be:

AttributeError: module 'math' has no attribute 'pi'

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions