2015-11-08 82 views
0

我正在学习Python中的类并决定创建一个仅用于练习,但在以特定方式显示实例属性时遇到问题:用另一个列表中的元素替换两个项目列表中的所有元素

from abc import ABCMeta, abstractmethod 

class Salad(object): 

    __metaclass__ = ABCMeta 

    seasoning = ["salt", "vinegar", "olive oil"]  # default seasoning 

    def __init__(self, name, type, difficulty_level, ingredients): 
     self.name = name 
     self.type = type 
     self.difficulty_level = difficulty_level 
     self.ingredients = ingredients 

    def prepare(self, extra_actions=None): 
     self.actions = ["Cut", "Wash"] 
     for i in extra_actions.split(): 
      self.actions.append(i) 
     for num, action in enumerate(self.actions, 1): 
      print str(num) + ". " + action 

    def serve(self): 
     return "Serve with rice and meat or fish." 


    # now begins the tricky part: 

    def getSaladattrs(self): 
     attrs = [[k, v] for k, v in self.__dict__.iteritems() if not k.startswith("actions")]  # I don't want self.actions 

     sortedattrs = [attrs[2],attrs[1], attrs[3], attrs[0]] 
     # sorted the list to get this order: Name, Type, Difficulty Level, Ingredients 

     keys_prettify = ["Name", "Type", "Difficulty Level", "Ingredients"] 
     for i in range(len(keys_prettify)): 
      for key in sortedattrs: 
       sortedattrs.replace(key[i], keys_prettify[i]) 
      # this didn't work 


    @abstractmethod 
    def absmethod(self): 
     pass 



class VeggieSalad(Salad): 

    seasoning = ["Salt", "Black Pepper"] 

    def serve(self): 
     return "Serve with sweet potatoes." 



vegsalad = VeggieSalad("Veggie", "Vegetarian","Easy", ["lettuce", "carrots", "tomato", "onions"]) 

基本上,我想打电话vegsalad.getSaladattrs()时,得到如下的输出:

Name: Veggie 
Type: Vegetarian 
Difficulty Level: Easy 
Ingredients: Carrots, Lettuce, Tomato, Onions 

,而不是这个(这是我所得到的,如果我只是告诉Python显示键和使用for循环的值):

name: Veggie 
type: Vegetarian 
difficulty_level: Easy 
ingredients: lettuce, carrots, tomato, onions 

在此先感谢!

回答

0

你的属性和值的列表似乎是这样的形式:

[['name', 'Veggie'], ['type', 'Vegetarian'], ['difficulty_level', 'Easy'], ['Ingredients', 'Carrots, Lettuce, Tomato, Onions' ]] 

所以下面应该产生你想要的输出:

for e in attrs: 
    if '_' in e[0]: 
     print e[0][:e[0].find('_')].capitalize() + ' ' \ 
     + e[0][e[0].find('_') + 1:].capitalize() + ': ' + e[1] 
    else:  
     print e[0].capitalize() + ': ' + e[1] 
+0

这奏效了!非常感谢:) – Acla

+0

没问题,很高兴帮助! –

相关问题