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 String isprintable()
Python Program to Slice Lists
Python Operator Overloading
Python Program to Find Factorial of Number Using Recursion
Python isinstance()
Python list()
Python Program to Check Leap Year
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Deep Learning in Python - LazyProgrammer
Python Dictionary popitem()
Python Multiple Inheritance
Python Program to Get the File Name From the File Path
How to Get Started With Python?
Python complex()
Python Program to Parse a String to a Float or Int
Python Program to Get the Class Name of an Instance
Python Program to Capitalize the First Character of a String
Python Set difference_update()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python String isdigit()
Python String isupper()
Python eval()
Python Global, Local and Nonlocal variables
Python Variables, Constants and Literals
Python Program to Check If a String Is a Number (Float)
Python Operators
Python divmod()
Python RegEx
Python Dictionary items()
Python Program to Check If Two Strings are Anagram
Python Set pop()
Python String upper()