What does delattr() function do in Python?


Python delattr()

The delattr() deletes an attribute from the object if the object allows it.

Syntax

The syntax of delattr() is −

delattr(object, name)

The delattr() method takes two parameters −

The delattr() doesn't return any value (returns None). It only removes an attribute (if object allows it).

Example

class Coordinate:

  x = 12

  y = -7

  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)

Output

This gives the output

Traceback (most recent call last):
('x = ', 12)
('y = ', -7)
File "C:/Users/~.py", line 28, in <module>
('z = ', 0)
print('z = ',point1.z)
--After deleting z attribute--
('x = ', 12)
AttributeError: Coordinate instance has no attribute 'z'
('y = ', -7)




Updated on: 20-Feb-2020

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements