Skip to content

Python delete class instance (Object) | Example code

  • by

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

A simple example code uses the del keyword Delete the object. After that try to run the func() function now, but 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 or suggestions on this Python instance tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading