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 Split a List Into Evenly Sized Chunks
Python Program to Print Hello world!
Python Program to Calculate the Area of a Triangle
Python Program to Catch Multiple Exceptions in One Line
Python vars()
Python abs()
Python Set difference_update()
Python Program to Generate a Random Number
Python Dictionary setdefault()
Python Dictionary popitem()
Python List count()
Python Dictionary values()
Python @property decorator
Python Program to Find Hash of File
Python int()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python bin()
Python String join()
Python Program to Differentiate Between del, remove, and pop on a List
Python Anonymous / Lambda Function
Python dir()
Python Dictionary pop()
How to get current date and time in Python?
Python Program to Delete an Element From a Dictionary
Python String split()
Python sorted()
Python Data Structures and Algorithms - Benjamin Baka
Python Program to Display Fibonacci Sequence Using Recursion
Python Set symmetric_difference_update()
Python Program to Print all Prime Numbers in an Interval
Python Exception Handling Using try, except and finally statement
Python Dictionary update()