Python delete class instance (Object) | Example code

Use the del keyword to delete class instance in Python. It’s delete references to the instance, and once they are all gone, the object is reclaimed.

del <Object name you want to delete>

Example of how to Python delete class instance

Simple example code uses the del keyword Delete the object. After that try to run the func() function now, it won’t run because the object is deleted.

class Test(object):
    def __del__(self):
        print("Object deleted")

    def func(self):
        print("Random function")


obj = Test()
obj.func()
del obj

obj.func()

Output: When we try to refer to a deleted object, it raises NameError

Python delete class instance

Do comment if you have any doubts and suggestions on this Python instance tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.