1

Let's say that I have a class "shoppingCart". I add items to the shopping cart: eggs, milk, cheese, bread, toothbrush, bacon, dish soap, potato chips, and bottled water.

class shoppingCart(object):
    def __init__(self):
        self.eggs = 12
        self.milk = 2
        self.cheese = 1
        self.bread = 0
        self.toothbrush = 1
        self.bacon = 10
        self.soap = 1
        self.chips = 2
        self.bottlewater = 24

myCart = shoppingCart()

Is it possible to create a group within the class, so that I could identify the number of items in my cart that fall into a specific category? For example, if I wanted to call all the attributes that are beverages (milk, water), or all the things that are non-food (toothbrush, soap), or things that are delicious (cheese, bacon, chips) - how could I go about doing that?

1 Answer 1

2

You shouldn't do that with only one class. I would create two clases. One would be a cart item, and the other one the shopping cart. For instance:

class cartItem(object):
    def __init__(self, amount=0):
        self.amount = amount
        self._is_beverage = False

    @property
    def is_beverage(self):
        return self._is_beverage

    @is_beverage.setter
    def is_beverage(self, value):
        self._is_beverage = value

And then the shopping cart:

class shoppingCart(object):
    def __init__(self):
        self._cart_items = []

    @property
    def cart_items(self):
        return self._cart_items

    @cart_items.setter
    def cart_items(self, value):
        self._cart_items = value

    def append_cart_item(self, new_cart_item):
        self._cart_items = self._cart_items.append(new_cart_item)

So you'd do:

myCart = shoppingCart()

milk = cartItem(amount=10)
milk.is_beverage = True

coke = cartItem(amount=2)
milk.is_beverage = True

myCart.cart_items = [milk, coke]

chips = CartItem(amount=20)
chips.is_beverage = False

myCart.append_cart_item(chips)

I would even make a specific class for each cart item type (I may improve the example later). I recommend you to learn more about classes and subclasses, for example here: http://www.jesshamrick.com/2011/05/18/an-introduction-to-classes-and-inheritance-in-python/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.