The delattr Function in Python

The delattr function in Python allows you to remove an attribute from a class, even from outside the class itself.

Syntax

delattr(class, attribute)

This function takes two arguments:

  • The name of the class that contains the attribute.
  • The name of the attribute you want to remove.

    A Practical Example

    Let's create a script with a class called Person.

    Inside this class, we’ll define an attribute called name.

    1. class Person():
    2. name = 'Andrea'
    3. delattr(Person, 'name')
    4. print(getattr(Person, 'name'))

    In line 3, we use the delattr() function to delete the name attribute from the Person class.

    Then, in line 4, we attempt to access and print the name attribute using the getattr() function.

    However, the script throws an error because the name attribute no longer exists in the class.

    Traceback (most recent call last):
    File, line 13, in <module>
    print(getattr(Person, 'name'))
    AttributeError: type object 'Person' has no attribute 'name'

    Once the attribute is removed from the class, it can no longer be accessed by the script.

    And that's how it works!

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Python Classes