In this tutorial we will learn about the python delattr() method and its uses.

Python delattr() Method

The delattr() method will delete the specific attribute from the particular object if that particular object allows it.

The syntax of delattr() method is:

delattr(object, name)

Python delattr() Method Parameters

The delattr() takes two parameters as an argument:

object – The name of the object from which attribute is to remove.

name – a string in which can be the name of the attribute to be removed from the object.

Let see some examples of the delattr() method.

Example 1: How does delattr() work?

class Coordinate:
  x = 10
  y = -5
  z = 0

point1 = Coordinate()

print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)

delattr(Coordinate, 'z')

print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)

# Raises Error
print('z = ',point1.z)

The output will be as follow:

x =  10
y =  -5
z =  0
--After deleting z attribute--
x =  10
y =  -5
Traceback (most recent call last):
  File "", line 19, in <module>
    print('z = ',point1.z)
AttributeError: 'Coordinate' object has no attribute 'z'

Here, attribute z is removed from the Coordinate class using delattr(Coordinate, ‘z’).

Example 2: Deleting Attribute using del Operator.

We can also delete attributes of an object using the del operator.

class Coordinate:
  x = 10
  y = -5
  z = 0

point1 = Coordinate()

print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)

# Deleting attribute z
del Coordinate.z

print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)

# Raises Attribute Error
print('z = ',point1.z)

Output:

x =  10
y =  -5
z =  0
--After deleting z attribute--
x =  10
y =  -5
Traceback (most recent call last):
  File "", line 20, in <module>
    print('z = ',point1.z)
AttributeError: 'Coordinate' object has no attribute 'z'

This will show the same output as example 1. 

Rules of python delattr() Parameters

delattr() does not return any value; it only removes an attribute. Default it will return None as an output.

 

Was this article helpful?
Share on: