Learning to Code Classes: Shrubbery Part Three
Shrubbery Part 3 - Classes
Overview
In this part of the assignment, you will refactor the Simple CLI Shrubbery Storefront from Part 2 to use classes. This will help you to further organize the code and make it more reusable and maintainable.
Objectives
By the end of this assignment, you will be able to:
- Use classes to structure your code and create reusable components
- Understand the benefits of object-oriented programming in organizing and maintaining code
Instructions
- Review the code from Part 2 of the assignment and identify components that can be converted into classes. Consider creating classes for the following components:
- Shrubbery
- Cart
- Store
- Create a
Shrubbery
class that represents a single shrubbery with properties such asname
andprice
. Add a method to display the shrubbery information. For example:
class Shrubbery:
def __init__(self, name, price):
self.name = name
self.price = price
def display(self):
print(f"{self.name}: ${self.price}")
- Create a
Cart
class that represents the shopping cart. The class should have methods for adding, removing, and displaying items in the cart, as well as calculating the total cost. For example:
class Cart:
def __init__(self):
self.items = {}
def add_item(self, shrubbery, quantity=1):
self.items[shrubbery] = self.items.get(shrubbery, 0) + quantity
def remove_item(self, shrubbery, quantity=1):
if shrubbery in self.items:
self.items[shrubbery] -= quantity
if self.items[shrubbery] <= 0:
del self.items[shrubbery]
def display(self):
for shrubbery, quantity in self.items.items():
print(f"{shrubbery.name} x {quantity}")
def total_cost(self):
return sum(shrubbery.price * quantity for shrubbery, quantity in self.items.items())
- Create a
Store
class that represents the shrubbery store. The class should have a list of available shrubberies and methods for displaying the shrubberies, processing user input, and managing the shopping cart. For example:
class Store:
def __init__(self, shrubberies):
self.shrubberies = shrubberies
def display_shrubberies(self):
for shrubbery in self.shrubberies:
shrubbery.display()
def process_user_input(self, input, cart):
# Implement the logic to process user input, add or remove items from the cart, and handle errors.
pass
- Update the main loop of the store to use instances of the
Store
,Cart
, andShrubbery
classes. For example:
store = Store(shrubberies)
cart = Cart()
while True:
print("Welcome to the Shrubbery Store!")
store.display_shrubberies()
choice = get_user_choice()
store.process_user_input(choice, cart)
...
- Test your refactored store thoroughly and make sure it works as expected.
- Add comments to your code to explain what each part does.
- As an optional exercise, consider adding more features to the store, such as applying discounts or allowing users to update the quantity of items in the cart.
- Reflect on how using classes has improved the organization, reusability, and maintainability of your