I have a simple best practice question rather than a technical / "how do I?" Question related to object oriented programming in Python.
I've recently been working on some OOP Python code that reads in data and stores them in a bespoke class. It's too detailed to post all the code here so I'll make a very simple example using cakes.
My main class - cake - looks something like the below and stores various data attributes about each 'cake'. Some variables are strings e.g. name while others are integers or floats e.g. layers.
class cake():
def __init__(self, name, layers, icing):
self.name = name
self.layers = layers
self.icing = icing
A large number of these objects are created when the data is read in, all of which are stored in a list:
cakebox = []
cakebox.append(cake("chocolate", 2, "Y"))
cakebox.append(cake("chocolate", 3, "Y"))
cakebox.append(cake("chocolate", 2, "N"))
cakebox.append(cake("lemon", 3, "Y"))
cakebox.append(cake("jamsponge", 2, "N"))
cakebox.append(cake("fruit", 1, "N"))
.........etc
The idea behind the 'cakebox' list is to act like simple 'database' from which results can be drawn. This is easily done using list comprehensions such as
icingcakes = [x for x in cakebox if x.icing == "Y"]
But some operations I'm finding I'm doing again and again, for example get all unique cake names:
uniquecakenames = list(set([x.name for x in cakebox]))
Given I use this code (or similar) several times would I be better making 'cakebox' a class with this code as a method, perhaps using 'list' as a super class, or am I over complicating things by creating a cakebox class in this example?
Please note that the real code is more complicated than my rather simplified cake example....! Also I've just typed this example on my iPad so please forgive me if there are minor code mistakes - hopefully it's enough to get across the main points.
All comments or suggestions welcome