书写类的基本思想

  1. 编写类时,先确定这个类的功能
  2. 向类中增加文档字符串,定义这个类的功能,并写出这个类的方法
  3. 写出方法,在doc中标出方法的接受参数和返回值
class Fridge:
    """
    this is a fridge.

    Methods:
    add_one(food_name): adds a single food_name to the fridge
    add_many(food_dict): adds a whole dictionary filled with food as keys and quantity as value
    has(food_name, quantity=1): check if the string food_name is in the fridge
    has_various( foods): determines if the dictionary food_name has enough of every element to satisfy a request
    get_one(food_name): remove one
    get_multi(food_dict):remove each type of food in dict
    """

    def __init__(self, items):
        """Optionally pass in an initial dictionary of items"""
        if not isinstance(items, dict):
            raise TypeError("Fridge require a dictionary but was given {0}".format(type(items)))

        self.items = items

    def __add_multi(self, food_name, quantity):
        """
        function:adds more than one of a food item
        :param food_name: str
        :param quantity: int
        :return: the number of items added
        attention:this should only be used internally,after the type checking has been done
        """
        # initial a new type of food to 0
        if food_name not in self.items:
            self.items[food_name] = 0

        self.items[food_name] = self.items[food_name] + quantity

    def add_one(self, food_name):
        """
        function:adds a single food_name to the fridge
        :param food_name: str
        :return: True
        attention:Raise a TypeError if food_name is not a string
        """
        if not isinstance(food_name, str):
            raise TypeError("add_one requires a string but given a {0}".format(type(food_name)))
        else:
            self.__add_multi(food_name, 1)
        return True

    def add_many(self, food_dict):
        """
        function:adds a whole dictionary filled with food as keys and quantity as value
        :param food_dict: dict{'food_name': 'quantity'}
        :return: none
        """
        if not isinstance(food_dict, dict):
            raise TypeError("add_many requires a dict but given a {0}".format(type(food_dict)))

        for item in food_dict.keys():
            self.__add_multi(item, food_dict[item])

        return True

    def has(self, food_name, quantity=1):
        """
        function:check if the string food_name is in the fridge
        :param food_name: string
        :param quantity: default to 1
        :return: enough --> true; empty --> false
        """
        if not isinstance(food_name, str):
            raise TypeError("has() needs a string but given a {0}".format(type(food_name)))
        return self.has_various({food_name: quantity})

    def has_various(self, foods):
        """
        has_various(foods): determines if the dictionary food_name has enough
        of every element to satisfy a request
        :param foods: dict
        :return: enough --> true; less --> false
        """
        try:
            for food_name in foods.keys():
                if self.items[food_name] < foods[food_name]:
                    return False
            return True
        except KeyError:
            print("there are no this kind of food ")
            return False

    def __get_multi(self, food_name, quantity):
        """

        :param food_name: string
        :param quantity: int
        :return: there isn't enough food --> False ; the number of items been removed
        """
        if food_name not in self.items.keys():
            print("state --> failed")
            print("this is no this kind of food that named '{0}'".format(food_name))
            return False
        else:
            if quantity > self.items[food_name]:
                print("state --> failed")
                print("{0} not enough {1}.".format(food_name, quantity))
                return False
            else:
                self.items[food_name] = self.items[food_name] - quantity
                print("state --> success")
                print("remove :", food_name, quantity)
                print("left:", food_name, self.items[food_name])
                return True

    def get_one(self, food_name):
        """
        function:remove one
        :param food_name: string
        :return: function ( __get_multi )
        """
        if not isinstance(food_name, str):
            raise TypeError("food_name needs a string but a {0} is given".format(type(food_name)))
        return self.__get_multi(food_name, 1)

    def get_multi(self, food_dict):
        """
        :param food_dict:
        :return: foodGetted
        """
        foodGetted = {}
        if not isinstance(food_dict, dict):
            raise TypeError("get_multi requires a dict but given a {0}".format(type(food_dict)))
        for food_name in food_dict.keys():
            if self.__get_multi(food_name, quantity=food_dict[food_name]):
                foodGetted[food_name] = food_dict[food_name]
        return foodGetted

    def display_items(self):
        print(self.items)


if __name__ == '__main__':
    print('*' * 20, "test initial", "*" * 20)
    fridge = Fridge({"egg": 6, "milk": 4, "cheese": 3})
    fridge.display_items()

    print('*' * 20, "test add_many", "*" * 20)
    fridge.add_many({"egg": 2, "grape": 3})
    fridge.display_items()

    print('*' * 20, "test has()", "*" * 20)
    print(fridge.has("egg", 6))
    print("-" * 20)
    print(fridge.has("apple"))

    print('*' * 20, "test get_one()", "*" * 20)
    fridge.get_one('apple')
    print("-"*20)
    fridge.get_one('egg')
    fridge.display_items()

    print('*' * 20, "test get_multi()", "*" * 20)
    get = fridge.get_multi({"egg": 6, "apple": 2, "milk": 3})
    fridge.display_items()
    print('you get the list of this:')
    print(get)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值