New to OOP & Python - question about storing multiple objects

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

My understanding of objects is still this way: I can define an object like:

class Meal:

And there are functions on it so 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 if I'm doing the right thing when it comes to storing a lot of objects. Right now, I keep them all on the 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 had soda in all the recorded meals, I sort through the list and count:

for each in listOfMeals

    if each.drink == 'soda':

        sodaCount = sodaCount + 1

? , - ( ), , - .

.

+3
5

, . , , : ?

( , ..), - ,

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

, , , :

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']
+6

ORM, SQLAlchemy, , ( " , -" ".).

+1

"" , sodaCount var.

def count_sodas(meals):
  return reduce(lambda count, meal: count + (1 if meal.drink == 'soda' else 0),
                meals, 0)
+1

. , . , , .

0

. , :

  • "" ( ), , class Meal(object):
  • , drink main . , , , . meal.drink == 'soda' meal.drink() == 'soda'
  • , (.. ), , , Meal.

, , Meals. . , 3 :

class Meals(object):
    def __init__(self):
        self.meals = []
    def __iter__(self):
        return iter(self.meals)
    def three_course(self):
        return [m for m in self.meal if m.starter and m.main and m.dessert]

This is a pretty far-fetched example, but you should get this idea. Also note that there are many ways to do this; you may want to subclass the list rather than wrap it. If you store food data in a database, consider the answer from @Ignacio. SQLAlchemy is great, and can be as simple or complex as you need.

0
source

All Articles