What does delattr() function do in Python?

PythonServer Side ProgrammingProgramming

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)




raja
Published on 12-Jan-2018 18:27:42
Advertisements