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
.
- class Person():
- name = 'Andrea'
- delattr(Person, 'name')
- 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!