hw06: Weight class
- Due before the beginning of class on Friday, January 23
The task
Write a class called Weight that keeps track of a single
weight and deals with conversion between grams and ounces.
For your conversions, use the value
28.3495
as the number of grams in one ounce.
Specifically, your Weight class needs to have:
- A constructor that takes a weight amount (a
float) and a unit (either"g"or"oz") - An attribute
.gthat returns or sets the weight in grams - An attribute
.ozthat returns or sets the weight in ounces
You might want to look at the section of the notes on “getters and setters” for some useful tools that will help you make a nice, clean solution.
How we will run your class
You need to write the Weight class in the file weight.py
so that code like the following will work:
from weight import Weight
apple = Weight(150.0, 'g')
grape = Weight(0.2, 'oz')
def print_weights(name, grams, ounces):
print(f"{name} weighs {round(grams,2)} grams, or {round(ounces,2)} ounces")
print_weights("Apple", apple.g, apple.oz)
print_weights("Grape", grape.g, grape.oz)
# take a bite of the apple
# this should affect the weight of the grams AND the ounces!
apple.g = 100.0
print_weights("Bitten apple", apple.g, apple.oz)
print_weights("Original grape", grape.g, grape.oz)
If your Weight class is implemented correctly, then running this
code will produce the following output:
Apple weighs 150.0 grams, or 5.29 ounces
Grape weighs 5.67 grams, or 0.2 ounces
Bitten apple weighs 100.0 grams, or 3.53 ounces
Original grape weighs 5.67 grams, or 0.2 ounces
The code
Go to your sd212 directory and run
git pull
You should see a new folder created for this hw, with the files provided and what you need to fill in.
If something goes weird with the git command, you should contact your instructor, but as a temporary work-around, you can always download the files directly from github here: https://github.com/sd212usna/sd212-folder
Submit command
To submit files for this homework, run one of these commands:
submit -c=sd212 -p=hw06 weight.py
club -csd212 -phw06 weight.py