Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New to OOP & Python -- Question About Storing Lots of Objects

Tags:

python

oop

I've just started out with Python and programming and I have a general question about storing many objects.

My understanding of objects so far is thus: I can define an object like:

class Meal:

And have functions on it such that I can find out about it for example Meal.drink returns 'soda' and Meal.main returns 'pizza'. So far, so good.

However, I'm not sure that I'm doing the right thing when it comes to storing lots of objects. Right now, I'm keeping them all in a list so that every time I want to record a new meal I do:

temp = Meal()

listOfMeals.append(temp)

If I want to find out how many times I've had soda in all the recorded meals I iterate through the list and count:

for each in listOfMeals

    if each.drink == 'soda':

        sodaCount = sodaCount + 1

Is this the best way to handle long lists of objects? It feels a bit clunky to me, but since I have no experience with object-oriented programming (and little programming experience in general) I'm not sure if I've overlooked something obvious.

Thank you for any help.

like image 301
CGPGrey Avatar asked Jan 27 '26 12:01

CGPGrey


1 Answers

It depends what you are going for. Every piece of code can be written more efficiently, but the question you should always ask yourself first is: Why does this code have to be faster?

If there is no reason to make that method faster (because the count is not used that much, the list of meals has just a hundred entries anyways, etc), you should just go with something simple like

sodacount = sum(1 for meal in listOfMeals if meal.drink=='soda')

On the other hand, if you need that count very often, you could wrap your list of meals in another object that stores and updates the count:

class MealList(object):
    # insert __init__, etc.

    def addMeal(self, meal):
        self._meals.append(meal)
        # update the count
        self.counts[meal.drink] += 1

    # insert method to remove meals

meals = MealList()
# add meals etc ....
print meals.counts['soda']
like image 145
Jochen Ritzel Avatar answered Jan 30 '26 00:01

Jochen Ritzel