Editor

Refactor Functions into a Class

Advanced · Refactor · from Python Classes and Objects: OOP from the Ground Up

From the lesson: Python Classes and Objects: OOP from the Ground Up

Imagine you own a bakery and you have a cookie cutter shaped like a star. Every time you press it into dough, you get a new star-shaped cookie. The cutter itself isn't a cookie - it's a blueprint for making cookies.

Read the lesson

Refactor this code into a ShoppingCart class. The class should have:

  • __init__ that creates an empty items list
  • add_item(self, name, price) that appends a tuple (name, price) to items
  • total(self) that returns the sum of all prices
  • __str__ that returns 'Cart: <N> items, total $<total>'
  • Then create a cart, add 'Apple' for 1.50 and 'Bread' for 3.00, and print the cart.

    # Original code to refactor:
    cart_items = []
    
    def add_item(cart, name, price):
        cart.append((name, price))
    
    def get_total(cart):
        return sum(price for _, price in cart)
    
    add_item(cart_items, 'Apple', 1.50)
    add_item(cart_items, 'Bread', 3.00)
    print(f'Cart: {len(cart_items)} items, total ${get_total(cart_items)}')
    # Refactor into a ShoppingCart class

    More Classes and Objects exercises

    All Python exercises · 50 practice problems · Object-Oriented Programming quiz