我可能会建议在寻找创建一个类,并使用OOP,而不是这样的事情。
class Recipe:
def __init__(self,name,ingredients):
self.name = name
self.ingredients = ingredients
def __str__(self):
return "{name}: {ingredients}".format(name=self.name,ingredients=self.ingredients)
toast = Recipe("toast",("bread"))
sandwich = Recipe("sandwich",("bread","butter","ham","cheese","butter","bread"))
随着“模板”变得越来越复杂,它不仅仅是一个数据定义,而且需要逻辑。使用一个类将允许你封装这个。
例如,我们的夹心以上有2个面包和2块黄油。我们可能要跟踪这个内部,就像这样:
class Recipe:
def __init__(self,name,ingredients):
self.name = name
self.ingredients = {}
for i in ingredients:
self.addIngredient(i)
def addIngredient(self, ingredient):
count = self.ingredients.get(ingredient,0)
self.ingredients[ingredient] = count + 1
def __str__(self):
out = "{name}: \n".format(name=self.name)
for ingredient in self.ingredients.keys():
count = self.ingredients[ingredient]
out += "\t{c} x {i}\n".format(c=count,i=ingredient)
return out
sandwich = Recipe("sandwich",("bread","butter","ham","cheese","butter","bread"))
print str(sandwich)
这给了我们:
sandwich:
2 x butter
1 x cheese
1 x ham
2 x bread
怎么样简单地做{“MENU_ITEM”:“成分”,...},而不是有“名'和'ing'作为额外的处理步骤。会让你的逻辑变得简单一些。 –
['collections.namedtuple'](http://docs.python.org/2/library/collections.html#collections.namedtuple)? – BrenBarn
甚至只是一个元组?成对的名称和值非常普遍。 – Eevee