我可能會建議在尋找創建一個類,並使用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