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:
Node.js vs Python for Backend Development
Python Program to Find All File with .txt Extension Present Inside a Directory
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python super()
Python Program to Check if a Number is Odd or Even
How to get current date and time in Python?
Python round()
Python Program to Display the multiplication Table
Python Exception Handling Using try, except and finally statement
Python zip()
Python Anonymous / Lambda Function
Python Program to Find the Size (Resolution) of a Image
Python Operator Overloading
Python Set union()
Python Set issuperset()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Custom Exceptions
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python String replace()
Python Set intersection_update()
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Check If a List is Empty
Python Closures
Python Program to Check the File Size
Python Numbers, Type Conversion and Mathematics
Python Program to Shuffle Deck of Cards
Python String center()
Python @property decorator
Python next()
Python setattr()
Python Program to Count the Number of Each Vowel
Python *args and **kwargs