Answer to Question #282351 in Python for Rao

Question #282351

Write an “abstract” class, Box, and use it to define some methods which any box object should have: add, for adding any number of items to the box, empty, for taking all the items out of the box and returning them as a list, and count, for counting the items which are currently in the box. Write a simple Item class which has a name attribute and a value attribute – you can assume that all the items you will use will be Item objects. Now write two subclasses of Box which use different underlying collections to store items: ListBox should use a list, and DictBox should use a dict.


1
Expert's answer
2021-12-23T16:27:34-0500
from abc import ABC, abstractmethod


class Item:
    def __init__(self, name, value):
        self.name = name
        self.value = value


class Box(ABC):
    def __init__(self, items):
        self.items = items

    @abstractmethod
    def add(self, add_items):
        pass

    @abstractmethod
    def empty(self):
        pass

    @abstractmethod
    def count(self):
        pass


class ListBox(Box):
    def __init__(self, items=None):
        if items is None:
            items = []
        super(ListBox, self).__init__(items)

    def add(self, *add_items):
        self.items.extend(add_items)

    def empty(self):
        items = self.items.copy()
        self.items.clear()
        return items

    def count(self):
        return len(self.items)


class DictBox(Box):
    def __init__(self, items=None):
        if items is None:
            items = {}
        super(DictBox, self).__init__(items)

    def add(self, *add_items):
        for add_item in add_items:
            self.items[add_item.name] = add_item.value

    def empty(self):
        items = self.items.copy()
        self.items.clear()
        return items

    def count(self):
        return len(self.items)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS