jaoc
jaoc

Reputation: 41

Need a class that keeps track of how many different types of classes have been created

I have an Animal class defined as:

class Animal:
    counter = 0
     
    def __init__(self, species, sound):
        self.species=species
        self.sound=sound
        Animal.counter += 1
        
    def make_sound(self):
        return self.sound
    
    def number_of_your_species(self):
        return self.counter 

I want number_of_your_species method to return how many different types of species have been created. The above code doesn´t work as it returns the TOTAL number that the class Animal has been instantiated. In other words, I want the below to return 2 (cats) and 1 (dog):

tom = Animal("cat","miau")
pluto = Animal("dog","guau")
misifu = Animal("cat","miau")

tom.number_of_your_species()
pluto.number_of_your_species()

Upvotes: 0

Views: 53

Answers (1)

Ismail Durmaz
Ismail Durmaz

Reputation: 2621

class Animal:
    counter = dict()
     
    def __init__(self, species, sound):
        self.species=species
        self.sound=sound
        if species not in Animal.counter:
            Animal.counter[species] = 0
        Animal.counter[species] += 1
        
    def make_sound(self):
        return self.sound
    
    def number_of_your_species(self):
        return Animal.counter[self.species]

Upvotes: 1

Related Questions