CS21 Lab 11: Sworthmore (objects)
Due Wednesday, December 9, before midnight
Please read through the entire lab before starting!
In this lab, you’ll write classes to represent Item and
Store objects that you’ll use to implement a text-based store front
program, Sworthmore. With some help
All of the standard style guidelines from previous labs still apply. Be sure to follow good top-down-design practices.
As you write programs, use good programming practices:
-
Use a comment at the top of the file to describe the purpose of the program (see example).
-
All programs should have a
main()function (see example). -
Use variable names that describe the contents of the variables.
-
Write your programs incrementally and test them as you go. This is really crucial to success: don’t write lots of code and then test it all at once! Write a little code, make sure it works, then add some more and test it again.
-
Don’t assume that if your program passes the sample tests we provide that it is completely correct. Come up with your own test cases and verify that the program is producing the right output on them.
-
Avoid writing any lines of code that exceed 80 columns.
-
Always work in a terminal window that is 80 characters wide (resize it to be this wide)
-
In
vscode, at the bottom right in the window, there is an indication of both the line and the column of the cursor.
-
Function Comments
All functions should include a comment explaining their purpose, parameters, return value, and describe any side effects. Please see our function example page if you are confused about writing function comments.
Goals
The goals for this lab assignment are:
-
Gain experience writing classes.
-
Gain experience reading and using classes and provided library functions.
1. Writing Classes
For this lab, you’ll be doing your work in three files:
-
item.py: This file will define aItemclass that you’ll use to represent the information you know about one item (i.e., the item’s name, a price, and a quantity). -
store.py: This file will define aStoreclass that you’ll use to list a collection ofItemobjects for sale. TheStoreclass will also have methods to sell items, restock items, and track the store’s total revenue. -
sworthmore.py: The main file that will contain yourmainfunction and supporting helper functions. The code in this file will "put everything together" by creating objects and calling methods on them to interact with Store and Item objects.
1.1. Testing
-
As always, you should test your program as you go.
-
Since you’re working with three files, it’s a good idea to put the tests for your class in the corresponding file.
-
Like we saw in lecture, this can be done by writing a
main()method, and then calling it at the bottom using:if __name__ == "__main__": main()This way, your testing code will run when you execute
python3 item.pyon the command line, but it won’t run when youimportfromiteminstore.pyorsworthmore.py.
2. The Item Class
The item.py file should contain a class definition for a class named Item. The Item class should have at minimum the following methods:
-
Constructor (
__init(…)__)-
The constructor should take three parameters: a
namestring, apricefloat, and aquantityinteger. It should save these variables as instance variables for the new object.
-
-
get_name(…): returns the name of the item. -
get_price(…): returns the price of the item. -
get_quantity(…): returns the current quantity of the item. -
__str__(…): returns a string representation of the item in the format:"<name> $<price> <quantity>"`. -
sell(…): takes an integer parameteramountand reduces the quantity of the item by that amount. This method should return the revenue generated by the sale (amount times price). If the amount is greater than the current quantity, it should not reduce the quantity and return 0. -
restock(…): takes an integer parameteramountand increases the quantity of the item by that amount. If the amount is negative, it should not change the quantity. This method does not return any value.
Before moving on to the Store class, add tests cases to a main
function at the bottom of the item.py file as describing in the Testing
section above. You should create at least two item objects using the
constructor, then you should test each of the methods you’ve written. You can
test __str__ by printing the object — you don’t need to call it directly.
def main():
item1 = Item("Soft Pretzel", 1.30, 50)
print(item1)
cost = item1.sell(5)
print("Cost of 5 items: $%.2f" % (cost))
print(item1)
print(item1.get_name())
print("Restocking 10 items...")
item1.restock(10)
print(item1)
print("Trying to sell 100 items...")
amt = item1.sell(100)
print("Amount sold: $%.2f" % (amt))
print(item1)
Soft Pretzel $1.30 50
Cost of 5 items: $6.50
Soft Pretzel $1.30 45
Soft Pretzel
Restocking 10 items...
Soft Pretzel $1.30 55
Trying to sell 100 items...
Amount sold: 0.00
Soft Pretzel $1.30 55
Note, the sample code above does not test all of the methods in the Item class and only has one item. You should add additional tests to your main() function to test all of the methods, and you should create at least two Item objects to test with.
3. The Store Class
The The Store class in store.py will manage a collection of Item objects. It should have at minimum the following methods:
-
Constructor (
__init(…)__)-
The constructor should take one parameters: a
name(str) of the store. It should save this variable as an instance variable for the new object. It should also initialize an empty list to hold the items in the store, and a balance variable to track the store’s revenue. The balance should be initialized to 0.0.
-
-
get_balance(…): returns the current balance of the store (float). -
get_name(…): returns the name of the store (str). -
get_number_of_items(…): returns the number of item types (not the total quantity) in the store (int). This will be the length of the list ofItemobjects in the store. -
__str__(…): returns a string representation of the store in the format:"<name> has a balance of $<balance> and has <number_of_items> items for sale." -
load_inventory(…): takes a filename (str) as a parameter. The file will contain one item per line in the following format:<name>,<price>,<quantity>. This method should read the file and create anItemobject for each line, adding it to the store’s inventory. You can assume that the file is formatted correctly.load_inventoryshould replace any previous inventory with the new inventory from the file. -
print_inventory(…): prints the inventory of the store. It should print each item in the store on a separate line using the__str__method of theItemclass. Each item printed should be preceded by an incremental label starting at 1. The output should look like the example below. -
sell_item(…): takes two parameters: an item ID (int) and a quantity (int). It the item ID is valid, it should call thesellmethod of the correspondingItemobject to sell the specified quantity. If the sale is successful (i.e., the quantity was available), it should add the revenue from the sale to the store’s balance and return the total amount of money made from the sale (float). If the sale is unsuccessful (i.e., not enough quantity in stock, or the item ID is invalid), it should return 0.0 and the balance should not change. -
restock_item(…): takes two parameters: an item ID (int) and a quantity (int). It the item ID is valid, it should call therestockmethod of the correspondingItemobject to restock the specified quantity. However, to restock an item, the store must have enough balance to pay for the restock. The cost of restocking is the item’s price times the quantity, times 0.90 (accounts for a 10% markup when selling). If the store has enough balance, it should reduce the store’s balance by the cost of restocking and returnTrue. If the store does not have enough balance, or the item ID is invalid, the restock_item method should returnFalseand the balance and inventory stock should not change.
Before moving on, add tests cases to a main function at the bottom of the
store.py file as describing in the Testing section above. You
should create a Store using the constructor. You can then stock multiple items in the store
using the load_inventory method. You should test each of the methods you’ve written. You can
test __str__ by printing the object.
You can pick any name for your store. A sample inventory file is provided for you in the lab directory called inventory.csv. You can use this file to test your load_inventory method, or you can create your own inventory file.
def main():
store = Store("Sheetz")
store.load_inventory("inventory.csv")
print(store)
store.print_inventory()
print("Selling 5 of item 1...")
revenue = store.sell_item(1, 5)
print("Revenue: %.2f" % (revenue))
print(store)
print()
store.print_inventory()
Sheetz has $0.00 in balance and 5 items for sale.
Inventory for Sheetz:
Item Price Qty
1. Soft Pretzel $1.30 50
2. Cheerwine $2.25 30
3. Water $1.20 100
4. Trail Mix $4.50 20
5. Pocky Sticks $3.00 12
Selling 5 of item 1...
Revenue: 6.50
Sheetz has $6.50 in balance and 5 items for sale.
Inventory for Sheetz:
Item Price Qty
1. Soft Pretzel $1.30 45
2. Cheerwine $2.25 30
3. Water $1.20 100
4. Trail Mix $4.50 20
5. Pocky Sticks $3.00 12
Note, the sample code above does not test all of the methods in the Store class. You should add additional tests to your main() function to test all of the methods.
4. Putting it all together in Sworthmore.py
The item.py file should contain a class definition for a class named
Item, and store.py should contain a class definition for a
class named Store. You will need to import these classes into
your Sworthmore.py file by typing:
from store import Store # (This will also import the Item class)
Even though your files are called item.py and
store.py, you import from item and store.
Python adds the .py automatically when looking for the file.
Like prior labs, this lab will present the user with a menu-based interface to make selections. The menu should look something like the following:
Welcome to Sheetz! Please choose an option: 1. Show inventory 2. Sell item 3. Restock item 4. Show balance 0. Quit Enter your choice:
You cannot assume that the user will type in an integer for this prompt. You also cannot assume that if they do type in an integer, it’ll be a valid menu selection. You need to validate that the user inputs a valid menu option.
You may pick any class appropriate name for your store.
Depending on what the user selects, you should do one of the following things:
4.1. Show inventory
This option should display the name of the store and display a list of items in the store. Each item should be displayed with an incremental index, a name, a price, and a quantity. The index number should start at 1 (not 0).
4.2. Sell item
This option should prompt the user for an item index and a quantity to sell. You should validate that the user inputs a valid index and a valid quantity (greater than 0). If the sale is successful, you should display the revenue generated by the sale. If the sale is unsuccessful, you should display an error message.
4.3. Restock item
This option should prompt the user for an item index and a quantity to restock. You should validate that the user inputs a valid index and a valid quantity (greater than 0). The store must have a balance sufficient to pay for the restock. Print a short message indicating the restock was successful or not.
4.4. Show balance
This option should display the current balance of the store.
4.5. Quit
This option should exit the program.
4.6. Example Output
Follow the link to view an example of the expected output
5. Requirements
|
The code you submit for labs is expected to follow good style practices, and to meet one of the course standards, you’ll need to demonstrate good style on six or more of the lab assignments across the semester. To meet the good style expectations, you should:
In addition, you’ll need to demonstrate good top-down design practices on two or more lab assignments across the semester. To meet the top-down design expectations, you should:
|
Your program should meet the following requirements:
-
Your program should be implemented in three files:
item.py,store.py, andsworthmore.py. -
Implement the methods described in the
ItemandStoreclass sections above. -
Include test code in the
ItemandStoreclasses that test each of your methods provided. These tests do not need to be interactive or ask the user for input. -
Implement the menu-based interface in
sworthmore.pyas described above. The program should continue to display the menu and prompt the user for input until the user selects the "Quit" option. -
Your
sworthmore.pyprogram should validate user input for the menu selection, item index, and quantity. It should not assume the user enters a valid integer. -
Your
sworthmore.pyprogram should use top-down design practices, with amain()function that calls other functions to implement subtasks. The functions included insworthmore.pywill primarily be for displaying the menu and getting user input. Much of the store interaction logic will be handled by theStoreandItemclasses.
6. Answer the Questionnaire
After each lab, please complete the short Google Forms questionnaire. Please select the right lab number (Lab 11) from the dropdown menu on the first question.
Once you’re done with that, you should run handin21 again.
Submitting lab assignments
Remember to run handin21 to turn in your lab files! You may run handin21
as many times as you want. Each time it will turn in any new work. We
recommend running handin21 after you complete each program or after you
complete significant work on any one program.
Logging out
When you’re done working in the lab, you should log out of the computer you’re using.
First quit any applications you are running, including your vscode editor, the browser and the
terminal. Then click on the logout icon (
) and choose "log out".
If you plan to leave the lab for just a few minutes, you do not need to log
out. It is, however, a good idea to lock your machine while you are gone. You
can lock your screen by clicking on the lock
icon.
PLEASE do not leave a session locked for a long period of time. Power may go
out, someone might reboot the machine, etc. You don’t want to lose any work!