SD 212 Spring 2024 / Homeworks


hw30: What is the Point of operator overloading?

  • Due before the beginning of class on Friday, April 12

References

This homework is based on our current unit on classes, focusing on operator overloading and Python’s “magic methods”.

This chapter from the “Python in a Nutshell” book talks about a number of these special methods and gives a good overview.

The ultimate reference is this page from the Python official documentation.

Your task

Create a file point.py that contains a class you write called Point to represent a 2-D coordinate with x and y.

Here’s how I will test your code:

from point import Point

p1 = Point(3,4)
p2 = Point(5,0)
print(p1)       # displays "(3,4)"
p3 = p1 + p2
print(p3)       # displays "(8,4)"
print(p1)       # still "(3,4)"
print(p2/2)     # displays "(2.5,0.0)"
midpoint = (p1 + p2) / 2
print(midpoint) # displays "(4.0,2.0)"

Running this file should produce the following output:

(3,4)
(8,4)
(3,4)
(2.5,0.0)
(4.0,2.0)

In order for this to work correctly, you will need to write these methods in your Point class:

  • __init__: Create a new Point from x and y coordinates
  • __add__: Add two Points to create a new Point
  • __truediv__: Divide a Point by a number to “scale” that Point by the number
  • __str__: Convert a Point to a string formatted like (XVALUE,YVALUE)

(Note: if you write any testing code inside your point.py file, make sure you put it under a if __name__ == '__main__' check.)

Submit command

To submit files for this homework, run one of these commands:

submit -c=sd212 -p=hw30 point.py
club -csd212 -phw30 point.py