This worksheet focuses on object-oriented programming.
(While last week included some lecture material on higher-order functions and lamdba, they are not included on this worksheet because you'll work with those topics a lot on Project 3. But you can check out the higher/ folder in the course sample code repo to see several examples, including ones that were mentioned in lecture but not covered in detail.)
Following the new policy, Problem 1 is different in that:
The main course materials to refer to for this worksheet are:
(Lecture videos are not linked on worksheets, but are also useful to review while working on worksheets. Video links can be found in the course course Blackboard site.)
Analogous to the classes discussed in our OOP lectures (for geometric objects Circle and Rectangle), create a Python class called Segment to store a line segment in the plane. The constructor should accept four arguments: x0,y0,x1,y1. The point (x0,y0) is then one endpoint of the segment, and (x1,y1) is the other endpoint. All four constructor arguments should be stored as attributes.
The following methods should be included:
translate(dx,dy)
- move the segment horizontally by dx
and vertically by dy
. This should modify the object, not returning anything.scale(factor)
- increase the length of the segment by a factor of factor
, keeping the center point the same. This is tricky, because the center point is not part of the data stored in the class! Feel free to skip this at first and come back to it later.__str__()
- make a reasonable human-readable string representation that includes the values of x0,y0,x1,y1.length()
- returns a float, the distance between the endpoints of the segment.Also, read the next problem before you start work on this.
This problem builds on the Segment class from problem 1.
Suppose the Segment class from Problem 2 is stored in a file geom.py
. Write a program to test the Segment class. It should do the following:
Any time you are tempted to test whether two floats are equal, please instead use a check of whether they differ by a very small amount, e.g. instead of
if x == y:
# stuff
use
if abs(x-y) < 0.000000001:
# stuff
This will help to avoid problems created by the fact that float operations are only approximations of the associated operations on real numbers. For example,
0.1 + 0.2 == 0.3
evaluates to False
because of the slight error in float addition (compared to real number addition), whereas
abs( 0.3 - (0.1+0.2) ) < 0.000000001
evaluates to True
.
Below you will find code that defines a class QuantityWithUnit
that is meant to store float quantities that also have a unit of measurement attached to them, such as 55 m
(55 meters), 2.8 s
(2.8 seconds), or 94.05 kg
(94.05 kilograms). Save it in a file qwu.py
on your computer, so you can import it with import qwu
. Read the code and familiarize yourself with what it does. Then try the following:
The final product of your work on this question could be a program that demonstrates all of these features.
class QuantityWithUnit:
"""A float quantity that also has a unit name, such as
kilograms, meters, seconds, etc."""
def __init__(self,qty,unit):
"""Create new quantity with units"""
self.qty = float(qty)
self.unit = unit
def __str__(self):
"""Make human-readable string version of quantity"""
return "{} {}".format(self.qty,self.unit)
def __repr__(self):
"""Make human-readable string version of quantity"""
return "QuantityWithUnits(qty={},unit={})".format(self.qty,self.unit)
def __add__(self,other):
"""Sum of two quantities requires them to have the same units"""
if not isinstance(other,QuantityWithUnits):
raise TypeError("Can only add a QuantityWithUnits to another QuantityWithUnits")
if self.unit != other.unit:
raise ValueError("Cannot add quantities with different units: {} and {}".format(self,other))
return QuantityWithUnits(self.qty+other.qty,self.unit)
def __sub__(self,other):
"""Difference of two quantities requires them to have the same units"""
if not isinstance(other,QuantityWithUnits):
raise TypeError("Can only subtract a QuantityWithUnits from another QuantityWithUnits")
if self.unit != other.unit:
raise ValueError("Cannot subtract quantities with different units: {} and {}".format(self,other))
return QuantityWithUnits(self.qty-other.qty,self.unit)
You should look at the previous problem before attempting this one, because it presumes familiarity with the QuantityWithUnit
class.
First, add support for testing equality to QuantityWithUnit
. Two quantities with unit should be considered equal if the float quantities are equal, and if the units are equal.
Now, consider adding support for multiplication as follows.
Multiplying two quantities with units results in an answer that has a different unit. For example, 11 kilograms multiplied by 20 seconds is equal to 220 kilogram-seconds.
However, it does make sense to multiply a quantity with units by a number that has no units at all. For example, if you have 16 apples that each have a mass of 0.1 kilograms, then the total mass is (0.1kg)*16 = 1.6kg.
Add an operator overloading feature to QuantityWithUnit
that allows such a quantity to be multiplied by a number as long as it is not an instance of QuantityWithUnit
. If you do this correctly, then the following tests should behave as the comments suggest. These assume that you have QuantityWithUnit
in a module called qwu
.