Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
delete
attribute
communitycreator

What is the delattr() function in Python?

Kainat Asif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The delattr() function in Python is used to delete an attribute from an object.

Syntax

The delattr() function can be declared as shown in the code snippet below.

delattr(obj, attr)
  • obj: The object from which the attribute attr will be deleted.
  • attr: The attribute that will be deleted from the object obj.

Return value

The delattr() function does not return any value. It simply removes the attribute from the object if the operation is successful.

Example

Consider the code snippet below which demonstrates the use of the delattr() function.

class Class1:
attr1 = "attribute1"
attr2 = "attribute2"
attr3 = "attribute3"
obj1 = Class1
try:
print('attr2: ' + obj1.attr2)
delattr(obj1, 'attr2')
print('attr2: ' + obj1.attr2)
except AttributeError:
print("Attribute not found!!")

Explanation

A class, Class1, is declared in lines 1-4. obj1 is an instance declared of Class1. The delattr() function is used in line 10 to delete the attribute attr2 of obj1. After deleting attr2 from obj1, trying to access attr2 returns the AttributeError.

RELATED TAGS

python
delete
attribute
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring