How to Delete an Attribute from Python Object?

Python – Delete an Attribute from Object

To delete an attribute from Python object, call delattr() builtin function, and pass the object and attribute name as arguments.

The following program statement is an example to call delattr() function for deleting attribute with name attrName from the Python object object.

delattr(object, attrName)

delattr() returns None.

Example

In this example, we will take an object A1 with attributes x and y. We will then use delattr() function and delete the attribute x.

Python Program

class A:
    def __init__(self, x, y):
        self.x = x
        self.y = y


A1 = A(2, 3)

print('Before deleting attribute from object A1')
result = hasattr(A1, 'x')
print(f'Does A1 has x? {result}')
result = hasattr(A1, 'y')
print(f'Does A1 has y? {result}')

# Delete the attribute x
delattr(A1, 'x')

print('\nAfter deleting attribute from object A1')
result = hasattr(A1, 'x')
print(f'Does A1 has x? {result}')
result = hasattr(A1, 'y')
print(f'Does A1 has y? {result}')
Run Code Copy

Output

Before deleting attribute from object A1
Does A1 has x? True
Does A1 has y? True

After deleting attribute from object A1
Does A1 has x? False
Does A1 has y? True

Summary

In this tutorial of Python Examples, we learned how to delete an attribute from a Python object.

Code copied to clipboard successfully 👍