Classes Basics in Python

Python code to implement classes. Here we are creating a class for fruits, then we will create two instances. Finally count them.

Source code :

class Fruit:
    total_count = 0
    
    def __init__(self,name):
        # This is a constructor
        Fruit.total_count += 1
        self.name = name
        
    def total():
        print(Fruit.total_count)
        

fruit1 = Fruit('Apple')     # Creates a Fruit Class Instance with name Apple
fruit2 = Fruit('Mango')     # Creates another  Fruit Class Instance with name Mango

Fruit.total() #Displays the total


Output :

2

Output :


                

Comments :