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
在此先感謝!
這奏效了!非常感謝:) – Acla
沒問題,很高興幫助! –