Python built-in Method - delattr()
www.igifaedit.com
The delattr()
method is a built-in function in Python that is used to delete an attribute from an object. It takes two arguments: the object whose attribute needs to be deleted, and the name of the attribute that needs to be deleted.
Here is the syntax for delattr()
method:
delattr(object, name)
where:
object
: the object whose attribute needs to be deleted.name
: the name of the attribute that needs to be deleted.
If the attribute does not exist, delattr()
raises an AttributeError
exception.
Here is an example of how to use delattr()
:
class Person: def __init__(self, name, age): self.name = name self.age = age p = Person("Alice", 25) # Delete the 'age' attribute from the 'p' object delattr(p, "age") # Try to access the 'age' attribute - this will raise an AttributeError print(p.age)
In this example, we define a Person
class with name
and age
attributes. We then create a Person
object p
with name
"Alice" and age
25. We then delete the age
attribute from p
using delattr()
. Finally, we try to access the age
attribute, which raises an AttributeError
because the attribute has been deleted.