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) 
copy

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.

ExampleEdit & Run
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))
copy
Output:
{'x': 2, 'y': 3} {'y': 3} [Finished in 0.010474203154444695s]

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 from obj.

Trying to access an attribute after it is  deleted will lead to an AttributeError exception being raised.

ExampleEdit & Run
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()
copy
Output:
Traceback (most recent call last):   File "<string>", line 13, in <module> AttributeError: 'Point' object has no attribute 'some_method' [Finished in 0.010364413261413574s]
ExampleEdit & Run
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')
copy
Output:
{'x': 10, 'y': 20} {'y': 20} {} Traceback (most recent call last):   File "<string>", line 16, in <module> AttributeError: 'Example' object has no attribute 'z' [Finished in 0.009972038678824902s]