The delattr()
function is used to delete the attribute with the specified name from a given object's namespace.
Attributes of an object refers to variables, methods, and other objects that are associated with it.
Syntax:
delattr(obj, name)
The required obj
argument specifies the object from whose namespace the attribute is to be deleted. The required name
argument specifies the name of the attribute to be deleted.
The function does not return any value. It raises an AttributeError
if the given name does not exist in the object's namespace.
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
obj = Point(2, 3)
print(vars(obj))
delattr(obj, 'x')
print(vars(obj))
The built-in vars() function returns the names associated with a namespace or an object. We used it above to view the change after deleting attribute x
from obj
.
Trying to access an attribute after it is deleted will lead to an AttributeError
exception being raised.
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
@staticmethod
def some_method():
pass
delattr(Point, 'some_method')
p = Point()
p.some_method()
class Example:
def __init__(self):
self.x = 10
self.y = 20
e = Example()
print(vars(e))
delattr(e, 'x')
print(vars(e))
delattr(e, 'y')
print(vars(e))
delattr(e, 'z')