Table of Contents
The delattr() deletes an attribute from the object (if the object allows it).
The syntax of delattr()
is:
delattr(object, name)
1. delattr() Parameters
delattr()
takes two parameters:
- object – the object from which name attribute is to be removed
- name – a string which must be the name of the attribute to be removed from the object
2. Return Value from delattr()
delattr()
doesn’t return any value (returns None
). It only removes an attribute (if the object allows it).
3. Example 1: How delattr() works?
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 z attribute--') print('x = ',point1.x) print('y = ',point1.y) # Raises Error print('z = ',point1.z)
Output
x = 10 y = -5 z = 0 --After deleting 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, attribute z is removed from the Coordinate class using delattr(Coordinate, 'z')
.
4. Example 2: Deleting Attribute Using del Operator
You can also delete attribute of an object using del operator.
class Coordinate: x = 10 y = -5 z = 0 point1 = Coordinate() print('x = ',point1.x) print('y = ',point1.y) print('z = ',point1.z) # Deleting attribute z del Coordinate.z print('--After deleting z attribute--') print('x = ',point1.x) print('y = ',point1.y) # Raises Attribute Error print('z = ',point1.z)
The output of the program will be the same as above.
Related posts:
Python Program to Check Armstrong Number
Python Set issuperset()
Python timestamp to datetime and vice-versa
Python String format()
Python String index()
Python String center()
Python Program to Transpose a Matrix
Python Dictionary keys()
Python Set symmetric_difference()
Python complex()
Python String maketrans()
Python abs()
Python len()
Python Dictionary setdefault()
Python String replace()
Python Program to Check the File Size
Python Dictionary popitem()
Python Program to Find Factorial of Number Using Recursion
Python Program to Remove Duplicate Element From a List
Python Object Oriented Programming
Python Dictionary pop()
Python Data Types
Python issubclass()
Python Variables, Constants and Literals
Python max()
Python Program to Count the Number of Each Vowel
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Convert Kilometers to Miles
Python Functions
Python open()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Type Conversion and Type Casting