Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

delattr()
python

What is delattr() in Python?

Educative Team

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.

delattr() is a Python method that is used for removing an attribute from an object (provided that the object allows it).

Syntax

delattr() can be called as:

delattr(object, name)

Parameters

The delattr() method takes the following parameters:

  • object: This is the object whose (desired) attribute should be removed.
  • name: This is a string that specifies the attribute that needs to be removed.

Return value

It must be noted that there is no value returned by the delattr() method. It returns None, as its job is merely getting rid of the desired attribute.

Code example

class marks:
Eng = 40
Urdu = 55
Math = 60
Marks = marks()
print('a = ',Marks.Eng)
print('b = ',Marks.Urdu)
print('c = ',Marks.Math)
delattr(marks, 'Math')
print('--After deleting Math attribute--')
print('a = ',Marks.Eng)
print('b = ',Marks.Urdu)
# Raises Error
print('c = ',Marks.Math)
Using delattr() to remove the unwanted attribute

Code explanation

  • Lines 1–4: We define a marks class.

  • Line 6: We create the object of the marks class.

  • Lines 8–10: We print the attributes of the marks class.

  • Line 12: We delete the Math attribute from the marks class, using delattr(marks, 'Math').

  • Lines 15–16: We print the attributes of the marks class again.

  • Line 19: We are shown an error, because the Math attribute has been removed from the class and we cannot display it.

Conclusion

The delattr() method is useful for removing certain attribute(s) of an object.

RELATED TAGS

delattr()
python
Copyright ©2022 Educative, Inc. All rights reserved

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