English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial básico Python

Controle de fluxo Python

Funções do Python

Tipos de Dados do Python

Operação de arquivo Python

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python delattr() usage and example

Python built-in functions

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

delattr() syntax is:

delattr(object, name)

delattr() parameters

delattr() has two parameters:

  • object-the object from which the name attribute is to be removed

  • name-a string, must be the one to be removed frominThe name of the deleted attribute

delattr() return value

delattr() does not return any value (returns None). It only deletes the attribute (if the object allows).

Example1: 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 the z attribute--
print('x = ', point1.x)
print('y = ', point1.y)
# Raise error
print('z = ', point1.z)

When running this program, the output is:

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

Here, use delattr(Coordinate, 'z') to delete the attribute 'z' from the Coordinate class.

Example2: Use del operator to delete attribute

You can also use the del operator to delete an object's attributes.

class Coordinate:
  x = 10
  y = -5
  z = 0
point1 = Coordinate() 
print('x = ', point1.x)
print('y = ', point1.y)
print('z = ', point1.z)
# Delete attribute z
del Coordinate.z
print('--After deleting the z attribute--
print('x = ', point1.x)
print('y = ', point1.y)
# Raise attribute error
print('z = ', point1.z)

The output of this program will be the same as above.

Python built-in functions