Python delete attribute

Share Your Love

In Python delete attribute, you can delete an attribute from an object using the del statement or the delattr() function. Here’s how you can use each method:

  1. Using the del statement:
    The del statement allows you to delete an attribute from an object by specifying the object name followed by the attribute name.
class MyClass:
    def __init__(self):
        self.attribute = 10

obj = MyClass()

# Delete the 'attribute' attribute using the 'del' statement
del obj.attribute

# Check if 'attribute' is present in obj
if hasattr(obj, 'attribute'):
    print("Attribute 'attribute' is present.")
else:
    print("Attribute 'attribute' is not present.")

Output:

Attribute 'attribute' is not present.
  1. Using the delattr() function:
    The delattr() function takes two arguments: the object from which you want to delete the attribute and the name of the attribute you want to delete.
class MyClass:
    def __init__(self):
        self.attribute = 10

obj = MyClass()

# Delete the 'attribute' attribute using the 'delattr()' function
delattr(obj, 'attribute')

# Check if 'attribute' is present in obj
if hasattr(obj, 'attribute'):
    print("Attribute 'attribute' is present.")
else:
    print("Attribute 'attribute' is not present.")

Output:

Attribute 'attribute' is not present.

Both the del statement and the delattr() function can be used to delete an attribute from an object. Choose the method that suits your needs and coding style.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter