Creating new instances of a class from user input

Question:

I am trying to make a weekly meal prep program in Python. Part of that program is having a database of recipes that the user has entered. I thought the best way to make this would be to make a class Recipe where it stores the title, ingredients (as a dictionary with the key being the ingredient and the amount being value) and then the instructions. However I can’t find a way to make a new variable each time I try to input a new recipe.

This is my class code

class Recipe:
  def __init__(self):
    ingredients = {}
    while True:
      ingredient = input('Type in an ingredient. Type finish when you have added in all the ingredients. ')
      if ingredient == 'finish':
        break
      amount = input("How much of this ingredient? ")
      ingredients[ingredient]=amount
    self.ingredients = ingredients
    self.title = input('What is the name of the recipe? ')
    self.instructions = input('Type out your recipe instructions; ')


meal1 = Recipe()
print(meal1.title)
print(meal1.ingredients)
print(meal1.instructions)

Basically this works for creating one recipe. But instead of the ”’ meal1 = Recipe()”’ I want to create a new recipe each time the user selects the option in the main menu to ‘add a recipe’ how can I accomplish this without making lots of pre-named variables.

Asked By: William

||

Answers:

if I understand your question properly, you want to create a fresh, brand new object every time that a user creates a recipe after inserting the instruction Type out your recipe instructions, then you can delete your object using __del__ function in your class.

class Recipe:
  def __init__(self):
  ingredients = {}
  while True:
  ingredient = input('Type in an ingredient. Type finish when you have added      in all the ingredients. ')
  if ingredient == 'finish':
    break
  amount = input("How much of this ingredient? ")
  ingredients[ingredient]=amount
  self.ingredients = ingredients
  self.title = input('What is the name of the recipe? ')
  self.instructions = input('Type out your recipe instructions; ')

def __del__(self):
  print("I have been destroyed.")

and to create a new object every time:

for i in range(5):
   meal1 = Recipe()
   print(meal1.title)
   print(meal1.ingredients)
   print(meal1.instructions)
   del meal1
   #print(meal1) # runs into NameError: name 'meal1' is not defined

note that how __del__ behaves, it may not be called every time if the reference to the object is not counted to zero. you may see this and this.

Answered By: Talkhak1313

I think the better approach is to separate between user input (menu) and the recipe class

class Recipe:
  def __init__(self):
    ingredients = {}
    while True:
      ingredient = input('Type in an ingredient. Type finish when you have added in all the ingredients. ')
      if ingredient == 'finish':
        break
      amount = input("How much of this ingredient? ")
      ingredients[ingredient]=amount
    self.ingredients = ingredients
    self.title = input('What is the name of the recipe? ')
    self.instructions = input('Type out your recipe instructions; ')


class Menu:
    def __init__(self):
        self.recipes = []
        while True:
            print("=" * 20)
            print('1. Add a recipe')
            print('2. Print the recipes')
            print('3. Quit')
            print("=" * 20)
            choice = input('What would you like to do? ')
            if choice == '1':
                self.add_recipe()
            elif choice == '2':
                self.print_recipes()
            elif choice == '3':
                break
            else:
                print('That is not a valid choice. Please try again.')

    def print_recipes(self):
        for recipe in self.recipes:
            print(recipe.title)
            print(recipe.ingredients)
            print(recipe.instructions)

    def add_recipe(self):
        recipe = Recipe()
        self.recipes.append(recipe)

Menu()

The recipe is saved in variable self.recipes. With this way, you can save as many recipes as you want.

Answered By: BlueBeret
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.