Skip to main content

Python delattr() Function

The delattr() function will delete the specified attribute from the specified object.

Syntax

delattr(object, name)

delattr() Parameters

Python delattr() function parameters:

ParameterConditionDescription
objectRequiredThe object from which name attribute is to be removed
nameRequiredThe name of the attribute you want to remove

delattr() Return Value

Python delattr() function does not return any value (returns None). It only removes an attribute (if the object allows it).

Examples

How to use delattr() function

class Info:
name = "TutorialReference"
lang = "Python"
site = "Google"

# Create an instance of the Info class
info_instance = Info()

# Print the 'lang' attribute before deletion
print("Before deletion:", info_instance.lang)

# Delete the 'lang' attribute using delattr()
delattr(Info, 'lang')

# Attempt to print the 'lang' attribute after deletion, which will raise an AttributeError
print("After deletion:", info_instance.lang)

output

Before deletion: Python
Traceback (most recent call last):
File "main.py", line 16, in <module>
print("After deletion:", info_instance.lang)
AttributeError: 'Info' object has no attribute 'lang'

Deleting attribute using del operator instead of delattr() function

You can also delete attribute of an object using del operator.

class Info:
name = "TutorialReference"
lang = "Python"
site = "Google"

# Create an instance of the Info class
info_instance = Info()

# Print the 'lang' attribute before deletion
print("Before deletion:", info_instance.lang)

# Delete the 'lang' attribute using the 'del' operator
del info_instance.lang

# Attempt to print the 'lang' attribute after deletion, which will raise an AttributeError
print("After deletion:", info_instance.lang)

output

Before deletion: Python
Traceback (most recent call last):
File "main.py", line 16, in <module>
print("After deletion:", info_instance.lang)
AttributeError: 'Info' object has no attribute 'lang'