Matthew L. Wright
Assistant Professor, St. Olaf College

# Homework 19: Classes and Objects

## CS 121 ⋅ Spring 2016

The following exercises ask you to modify the Point class defined in the text. Upload the Python file(s) containing your solutions to the following exercises to Moodle for HW19.

1. Add to the Point class a method is_origin that returns True if the point has coordinates (0,0) and False otherwise.

`def is_origin(self):`
2. Add to the Point class a method slope_from_origin that returns the slope of the line between the point and the origin.

Recall that slope is defined as (change in y)/(change in x). Note that slope is undefined if change in x is zero; in this case, your function should return None.

For example, Point(6, 3).slope_from_origin() should return 0.5.

This is Exercise 3 in the Classes and Objects: Basics section of the online Python text.

3. Add to the Point class a method reflect_x that returns a new Point, which is the reflection of the point across the x-axis.

For example, Point(6, 3).reflect_x() should return a Point object with coordinates (6, -3).

This is Exercise 2 in the Classes and Objects: Basics section of the online Python text.

4. Add to the Point class a method move that takes two parameters, dx and dy. This method will modify the properties of the point so that the point moves the given distances in the x and y directions.

For example, consider the following code:

``` p = Point(1, 6) p.move(3, 2) ```

After the above lines of code have run, p will have coordinates (4, 8).

This is Exercise 5 in the Classes and Objects: Basics section of the online Python text.

5. Add to the Point class a add method that "adds" two points by adding the corresponding x- and y-coordinates. Your function should take a Point as a parameter and add it to the Point instance whose method is called, returning a new Point.

For example, consider the following code:

``` p = Point(1, -1) q = Point(4, 3) s = p.add(q) ```

After the above lines of code have run, s will be a Point with coordinates (5, 2), while p and q will still have their original coordinates.