मैं शायद एक वर्ग बनाने और कुछ इस तरह के लिए बजाय 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
स्रोत
2013-10-30 04:20:29
कैसे बस { 'menu_item': 'सामग्री', ...} करने के बारे में के बजाय एक 'नाम होने एक अतिरिक्त प्रसंस्करण चरण के रूप में 'और' आईएनजी '। आपके तर्क को थोड़ा सरल बना देगा। –
['collections.namedtuple'] के बारे में कैसे करें (http://docs.python.org/2/library/collections.html#collections.nametuple)? – BrenBarn
या यहां तक कि सिर्फ एक टुपल? नाम और मूल्यों के जोड़े बहुत आम हैं। – Eevee