只需遍历列表并检查每一个。
你需要稍微移动一下代码,因为class def
需要在类的使用之上,而且它还使用了一个小的c
. 您还应该注意它未被识别的情况。
你也拼错了嘉士伯:/
class Beer:
def __init__ (self, name, taste):
self.name = name
self.taste = taste
beers = []
beers.append(Beer('Carlsberg', 'tasty'))
beers.append(Beer('Guinness', 'bitter'))
beers.append(Beer('Lef', 'perfect'))
def howIsBeer (name):
taste = "I have no idea"
for beer in beers:
if beer.name == name:
taste = beer.taste
print taste
howIsBeer("Carlsberg") # tasty
不过,我会这样做(使用此处的字典可以灵活地拥有多个属性):
beers = {}
beers["Lef"] = {"taste": "tasty"}
beers["Staropramen"] = {"taste": "tasty"}
beers["Peroni"] = {"taste": "tasty"}
beers["Coors Light"] = {"taste": "What is this?!"}
def howIsBeer (name):
taste = "I have no idea"
if name in beers:
taste = beers[name]["taste"]
print taste
howIsBeer("Lef")
如果你只是想存储口味,那么你可以这样做:
beers = {}
beers["Lef"] = "tasty"
beers["Staropramen"] = "tasty"
beers["Peroni"] = "tasty"
beers["Coors Light"] = "What is this?!"
def howIsBeer (name):
taste = "I have no idea"
if name in beers:
taste = beers[name]
print taste
howIsBeer("Lef")
如果您正在寻找存储一系列对象 - 正如您在问题中提到的那样 - 那么您需要一个对象字典 -而不是作为类变量的字典。
IE
beers = {}
def add_beer(beer):
beers[beer.name] = beer
然后获取您正在查看的啤酒的数据;
if beer in beers:
beers[beer].taste
这可以扩展到任何对象类型,我相信这正是您正在寻找的;
例如
cheeses = {}
add_cheese(cheese):
cheeses[cheese.name] = cheese
在哪里
class cheese:
def __init__(self, name, smelliness, hardness, colour, country):
self.name = name
self.smelliness = smelliness
self.hardness = hardness
self.colour = colour
self.country = country