Constructing my first Point Class

So I was showing someone how to build a Point Class today, and realized that this is actually the first time I’ve ever built one.

points

As a quick sidenote, in programming, the Point Class is the quintiseential example class representing a single point in cartesian space. The Point Class is usually used to teach Objects and Classes in an introductory Object Oriented Programming course in computer science.

However, not ever having taken a computer science course, and this also being my birthday, I felt that it is refreshing to share something simple and archetypal.

So here it is!

 import math

 class PointError(Exception):
     pass

class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return 'Point(%s, %s)' % (self.x, self.y)

    @classmethod
    def distance(cls, p1, p2):
        if not isinstance(p1, cls):
            raise PointError('%s is not of class %s' % (p1, cls))
        if not isinstance(p2, cls):
            raise PointError('%s is not of class %s' % (p2, cls))
        return math.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2)

Using the point class should be pretty trivial.

We also utilize inheritence in order to build a simple PointError class. This means that passing anything other than an instance of our Point class into the distance() function will raise the following error.

>>> Point.distance(p1, 10)
---------------------------------------------------------------------------
PointError                                Traceback (most recent call last)
---->01 Point.distance(p1, 10)
     19         if not isinstance(p2, cls):
---->20             raise PointError('%s is not of class %s' % (p2, cls))
     21         return math.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2)
PointError: 10 is not of class Point

As well we also build a method bound to the Point Big P class rather than a normal method bound to an instance little p. This may seem slightly esoteric but it makes sense, because it allows us to use the isinstance() function to properly check if a point is an instance of the class without needing us to awkwardly pass in the name of the class like so.

class Point:
..
    def distance(self, p2):
        if not isinstance(p2, Point):
..

And there you have it!

Pretty simpel right?


P.S Here’s the code to generate the plot in a Jupyter/IPython notebook. Be sure that you have the Humor Sans fontface and to clear your fontcache to get it to render correctly :)
# Set Output Type
%matplotlib inline

import matplotlib.pyplot as plt
import seaborn as sns

# Default Styling
sns.set_style('whitegrid')
sns.set_context('notebook', font_scale=1.5, rc={'lines.linewidth': 2.5})

# Pythagorean Theorem Anyone?
plt.plot([1,2], [2,2], 'ro-') # a^2
plt.plot([2,2], [2,4], 'ro-') # b^2
plt.plot([1,2], [2,4], 'o-')  # c^2

# Annotations
plt.title('Point Classes')    # Title
plt.xlabel('X Axis')          # X Axis
plt.ylabel('Y Axis')          # Y Axis

plt.axis([0,3,0,5])           # Axis Ranges

plt.annotate(
    'Point.distance(p1, p2)', # Arrow
    xy=(1.5, 3.2),
    xytext=(0.5, 4),
    arrowprops=dict(facecolor='black', shrink=0.1),
)

# Text Labels
plt.text(0.8, 2, 'p1')
plt.text(1.8, 4, 'p2')
plt.text(1.3, 1.6, 'p2.x - p1.x')
plt.text(2.1, 3.0, 'p2.y - p1.y')

plt.xkcd()
plt.tight_layout()

plt.show()

points

Cheers!


Comments

comments powered by Disqus