Deleting an instance of a Class in Python

This program will show you how to delete a instance of a class.

Source code :




class Fruit:
    count = 0
    
    def __init__(self, name, taste):
        self.name = name
        self.taste = taste
        Fruit.count += 1
        
    def displayCount(self):
        print("Total Fruits count " + str(Fruit.count))
        
    def displayFruit(self):
        print("Name : " + self.name + " Taste: " + self.taste )
        
        
f1 = Fruit('Apple', 'sweet')
f1.displayCount()

del f1  #This will delete the class instance

f1.displayCount() #Error 


Output :

NameError: name f1 is not defined

Notes :

Since we have delete the class instance f1 variable, further usage of the f1 variable will show an error


Output :


                

Comments :