• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Delete Attribute From an Object in Python

Delete Attribute From an Object in Python

Author: Aditya Raj
Last Updated: August 22, 2022

Python is an object-oriented programming language. We often use objects defined with custom classes while programming. In this article, we will discuss how we can delete an attribute from an object in Python. 

Delete Attribute From an Object using the del statement in Python

The del statement can be used to delete any object as well as its attributes. The syntax for the del statement is as follows.

del object_name

To see how we can delete an attribute from an object, let us first create a custom class Person with the attributes name, age, SSN, and weight.

class Person:
    def __init__(self, name, age, SSN, weight):
        self.name = name
        self.age = age
        self.SSN = SSN
        self.weight = weight

Now we will create an object named person1 of the Person class. After that, we will delete the attribute weight from the person1 object using the del statement as shown below. 

class Person:
    def __init__(self, name, age, SSN, weight):
        self.name = name
        self.age = age
        self.SSN = SSN
        self.weight = weight

    def __str__(self):
        return "Name:" + str(self.name) + " Age:" + str(self.age) + " SSN: " + str(self.SSN) + " weight:" + str(
            self.weight)


person1 = Person(name="Will", age="40", SSN=1234567890, weight=60)
print(person1)
del person1.weight
print(person1)

Output:

Name:Will Age:40 SSN: 1234567890 weight:60
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 16, in <module>
    print(person1)
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 10, in __str__
    self.weight)
AttributeError: 'Person' object has no attribute 'weight'

In the above example, you can see that we can print the attribute weight before the execution of the del statement. When we try to print the attribute weight after the execution of the del statement, the program runs into the AttributeError exception saying that there is no attribute named weight in the object. Hence, we have successfully deleted the attribute from the object using the del statement in python. 

Delete Attribute From an Object Using the delattr() Function in Python

We can also delete an attribute from an object using the delattr() function. The delattr() function accepts an object as its first input argument and the attribute name as its second input argument. After execution, it deletes the attribute from the given object. You can observe this in the following example.

class Person:
    def __init__(self, name, age, SSN, weight):
        self.name = name
        self.age = age
        self.SSN = SSN
        self.weight = weight

    def __str__(self):
        return "Name:" + str(self.name) + " Age:" + str(self.age) + " SSN: " + str(self.SSN) + " weight:" + str(
            self.weight)


person1 = Person(name="Will", age="40", SSN=1234567890, weight=60)
print(person1)
delattr(person1, "weight")
print(person1)

Output:

Name:Will Age:40 SSN: 1234567890 weight:60
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 16, in <module>
    print(person1)
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 10, in __str__
    self.weight)
AttributeError: 'Person' object has no attribute 'weight'

You can observe that we are able to print the weight attribute of the person1 object before the execution of the delattr() function. After execution of the delattr() function, the program raises the AttributeError exception when we try to print the weight attribute of the person1 object denoting that the attribute has been deleted.

If we pass an attribute name that doesn’t already exist in the object, it raises the AttributeError exception as shown below.

class Person:
    def __init__(self, name, age, SSN, weight):
        self.name = name
        self.age = age
        self.SSN = SSN
        self.weight = weight

    def __str__(self):
        return "Name:" + str(self.name) + " Age:" + str(self.age) + " SSN: " + str(self.SSN) + " weight:" + str(
            self.weight)


person1 = Person(name="Will", age="40", SSN=1234567890, weight=60)
print(person1)
delattr(person1, "BMI")
print(person1)

Output:

Name:Will Age:40 SSN: 1234567890 weight:60
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 15, in <module>
    delattr(person1, "BMI")
AttributeError: BMI

Here, you observe that we have tried to delete the BMI attribute from the person1 object that is not present in the object. Hence, the program runs into the AttributeError exception.

Conclusion

In this article, we have discussed two ways to delete an attribute from an object in python. To learn more about objects and classes, you can read this article on classes in python. You might also like this article on list comprehension in python. 

Suggested Readings:

  • Developing Chat Application in Python with Source Code
  • Polynomial Regression Using sklearn Module in Python

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us