When I call the classmethod within the init , where I initialize an object, the classmethod count_genre is called each time, incrementing values that were there before. I'd only like to call the method once.
class Furniture:
materials = []
material_count = {}
def __init__(self, name, material):
self.name = name
self.material = material
Furniture.materials.append(self.material)
Furniture.count_material()
@classmethod
def count_material(cls):
for material in cls.materials:
cls.material_count[material] = cls.material_count.get(material, 0) + 1
Furniture("Chair", "Wood")
Furniture("Cushion", "Cotton")
Furniture("Table", "Glass")
print(Furniture.material_count)
This is what I get on my terminal: {'Chair': 3, 'Cushion': 2, 'Table': 1}
This is what I want to get: {'Chair': 1, 'Cushion': 1, 'Table': 1}
Use
Furnitureto model a piece of furniture. Use a separate class to model information about a particular set of pieces of furniture.