The delattr()
function in Python is used to delete an attribute from an object. It takes two arguments: the object from which the attribute is to be deleted, and the name of the attribute.
Here's the syntax for using the delattr()
function:
delattr(object, attribute_name)
object
: This is the object from which the attribute will be deleted.attribute_name
: This is a string representing the name of the attribute that will be deleted.Here's an example that demonstrates the usage of delattr()
:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 25)
print(person.name) # Output: Alice
delattr(person, "name")
print(person.name) # Raises an AttributeError: 'Person' object has no attribute 'name'
In the above example, we create a Person
class with two attributes: name
and age
. We create an instance of the Person
class called person
and initially assign the name "Alice" to the name
attribute. After calling delattr(person, "name")
, the name
attribute is deleted from the person
object. When we try to access person.name
again, it raises an AttributeError
because the attribute no longer exists.
It's important to note that if the attribute doesn't exist in the object, delattr()
will raise an AttributeError
.