I am working on a little text base resultant game, but I am having troubling creating this list of Food, I want to put all my Food (either Burger, or Hotdog) in listOfFood. In my example I only included two, but they are all “base” on food.
Later then I will iterate through my listOfFood to do something. I abstracted my code to ask question (because it has too many lines, and the other information is not related to it).
class Food():
def __init__(self):
self.name = 'Food'
class HotDog(Food):
def __init__(self):
Food.__init__(self)
class Burger(Food):
def __init__(self):
Food.__init__(self)
def createFoodList(myOrders):
# A list that contain all the food (either Burger or Hotdog)
listOfFood = []
# Depend what is the type of the food, create that many food object
# and then append it to the list of food
if myOrders[0][0] == 'HotDog':
for number in myOrder[0][1]:
listOfFood.append(HotDot())
if myOrders[0][1] == 'Burger':
for number in myOrder[0][1]:
listOfFood.append(Burger())
return listOfFood
todayOrders = [['HotDog', 10], ['Burger', 5]]
print(createFoodList(todayOrders))
I wonder if I can use list comprehension or similar method to make my createFoodList function better? Because my idea is to have many different kind of Food, so if I can return this list of food, base on todayOrders list ['type of food', count] and return [food, food, food.. ]. The way I am doing right now is really complicated and long (I have a feeling this is not the right way).
Thank you very much.
Edit: Besides the list comprehension, what can I do to replace the if statements in createFoodList? It is decide on the [[food, count], [food, count]..], and I create that food and append it to my list.
foodmap[f]evaluates to eitherHotDogorBurger(these are classes – not class names, the classes themselves). Callingsomeclass()creates an instance ofsoemclassand passes no arguments when callingsomeclass.__init__. Hencefoodmap[f]()combines both of these – it looks up the class infoodmapand uses the class to create an instance of that class.