A document from MCS 260 Fall 2021, instructor David Dumas. You can also get the notebook file.

# MCS 260 Fall 2021 Worksheet 10¶

• Course instructor: David Dumas

## Topics¶

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.)

## Problem 1 treated differently¶

Following the new policy, Problem 1 is different in that:

• Tuesday lab students: Problem 1 will be presented and solved as a group, in a discussion led by your TA.
• Thursday lab students: Please attempt problem 1 before coming to lab. Bring a solution, or bring questions. The problem will be discussed as a group.

## Resources¶

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.)

## 1. Segment class¶

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.

## 2. Equality for segments¶

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:

• Create a segment and check that the attributes x0,y1, etc. exist.
• Scale a segment and confirm that the new endpoints are as expected.
• Translate a segment and confirm that the new endpoints are as expected.
• Test that a segment that you choose to ensure its length is computed correctly.

## IMPORTANT NOTE¶

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.

## 3. Quantity with unit¶

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:

• Create an instance M of this class to represent 19 kilograms
• See how the REPL displays that value
• Try printing M
• What happens when you add M to itself?
• What happens when you subtract M from itself?
• Create an instance T of this class to represent 3600 seconds
• What happens when you add M and T?

The final product of your work on this question could be a program that demonstrates all of these features.

In [ ]:
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)
"""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)


## 4. Improving the quantity with unit class¶

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.

## Revision history¶

• 2021-10-25 Initial release