AttributeError:'bool'对象没有属性'keys'

时间:2013-08-01 06:17:08

标签: python

我是这个网站上的新手,我也是编程的新手,我正在尝试使用python 3.1上的初学者学习python。我遇到了一个例子,不管我尝试什么都行不通,我已经写了大约10次写错,但看起来我在书中看到的却是这样。这是一个例子:

冰箱类

#!/usr/bin/env
class Fridge:
    """methods:
    has(food_name [, quantity])-chk if string is in the fridge
    has_various(foods)-chk if enough food is in the fridge
    add_one(food_name) -adds 1 food
    add_many(food_dict)- adds dict to fridge
    get_one(food_name)- take out 1 food
    get_many(food_dict) - a dict out of fridge
    get_ingred(food)- if passed an obj get the list of __ingredients__
    """
    def __init__(self, items={}) :
        if type(items) != type({}):
            raise typeError("Fridge req a dict but was given %s" %  type(items))
        self.items=items
        return
    def __add_multi(self, food_name, quantity):
        if (not food_name in self.items):
            self.items[food_name]=0
        self.items[food_name]=self.items[food_name]+quantity
    def add_one(self, food_name):
        if type(food_name) != type(""):
            raise TypeError ("add_one requires a string givem a %s " % type(food_name))
        else:
            self.__add_multi(food_name, 1)
        return True
    def add_many(self, food_dict):
        if type(food_dict) != type({}):
            raise TypeError ("add_many requires a dict, got a %s" % type(food_dict))
        for item in food_dict.keys() :
            self.__add_multi(item, food_dict[item])
        return
    def has(self, food_name, quantity=1):
        return self.has_varoius({food_name:quantity})
    def has_various(self, foods):
        try:
            for food in foods.keys():
                if self.items[food] < foods[food]:
                    return False
            return True
        except KeyError:
            return Fasle
    def __get_multi(self, food_name, quantity):
        try:
            if (self.items[food_name] is None) :
                return False
            if (quantity > self.items[food_name]):
                return False
            self.items[food_name] = self.items[food_name] - quantity
        except KeyError:
            return False
        return quantity
    def get_one(self, food_name):
        if type(food_name) !=type(""):
            raise TypeError("get_one requires a string and was given a %s" % type(food_name))
        else:
            result=self.__get_multi(food_name, 1)
            return result
    def get_many(self, food_dict):
        if self.has_various(food_dict):
            foods_removed={}
            for item in food_dict.keys():
                foods_removed[item]=self.__get_multi(item, food_dict[item])
            return foods_removed
    def get_ingredients(self, food):
        try:
            ingredients=self.get_many(food.__ingredients())
        except AttributeError:
            return False
        if ingredients!=False:
            return ingredients

煎蛋卷类

 #!/usr/bin/env python3.3
class Omelet:

    def __init__(self, kind="cheese"):
        self.set_kind(kind)
        return

    def __ingredients__(self):
        return self.needed_ingredients

    def get_kind(self):
        return self.kind

    def set_kind(self, kind):
        possible_ingredients=self.__known_kinds(kind)
        if possible_ingredients == False :
            return False
        else:
            self.kind=kind
            self.needed_ingredients= possible_ingredients

    def set_new_kind(self, name, ingredients):
        self.kind=name
        self.needed_ingredients= ingredients
        return

    def __known_kinds(self, kind):
        if kind == "cheese":
            return {"eggs":2, "milk":1, "cheese":1}
        elif kind == "mushroom":
            return {"eggs":2, "milk":1, "cheese":1, "mushroom":2}
        elif kind == "onion":
            return {"eggs":2, "milk":1, "cheese":1, "onion":1}
        else:
            return False

    def get_ingredients(self, fridge):
        self.from_fridge= fridge.get_ingredients(self)

    def mix(self):
        for ingredient in self.from_fridge.keys():
            print("mixing %d %s for the %s omelet" % (self.from_fridge["ingredient"], ingredient, self.kind))
        self.mixed=True

    def make(self):
        if self.mixed == True:
            print("Cooking the %s omelet!" % self.kind)
            self.cooked = True 

这是我如何调用类以及我如何使用类和我得到的错误

>>> exec(open("/home/knoppix/test/fridge.py").read())
>>> exec(open("/home/knoppix/test/omelet.py").read())
>>> o=Omelet("cheese")
>>> f=Fridge({"cheese":5, "milk":4, "eggs":12})
>>> o.get_ingredients(f)
>>> o.mix()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 41, in mix
AttributeError: 'bool' object has no attribute 'keys'

如果代码中有输入错误,请原谅我,这正是我在书中找到的内容!

2 个答案:

答案 0 :(得分:2)

def get_ingredients(self, fridge):
    self.from_fridge= fridge.get_ingredients(self)

在此功能中,您的fridge.get_ingredients()可能会返回False

因此self.from_fridge的值Boolean没有keys()方法。

您可能希望在mix()方法中添加适当的检查。

答案 1 :(得分:1)

功能&#34; __ known_kinds(kind)&#34;应该优选地返回{}以保持一致,而不是不同的对象类型,尽管&#34;无&#34;优于&#34;错误&#34;。

    if kind == "cheese":
        return {"eggs":2, "milk":1, "cheese":1}
    elif kind == "mushroom":
        return {"eggs":2, "milk":1, "cheese":1, "mushroom":2}
    elif kind == "onion":
        return {"eggs":2, "milk":1, "cheese":1, "onion":1}
    else:
        return {}

然后你只需要在mix()方法中处理字典类型。 else也可以从mix()中删除,因为如果dict == {}将引发异常。

def mix(self):
    if self.from_fridge == {}:
        raise IndexError("self.from_fridge returns Nothing")

    for ingredient in self.from_fridge.keys():     

...