The Python Book
 
point class
20151022

Define a point class

  • with an x and y member
  • with methods to 'autoprint'

Definition

import math

class P:
    x=0
    y=0
    def __init__(self,x,y):
        self.x=x
        self.y=y

    # gets called when a print is executed
    def __str__(self):
        return "x:{} y:{}".format(self.x,self.y)

    # gets called eg. when a print is executed on an array of P's
    def __repr__(self):
        return "x:{} y:{}".format(self.x,self.y)


# convert an array of arrays or tuples to array of points
def convert(in_ar) :
    out_ar=[]
    for el in in_ar:
        out_ar.append( P(el[0],el[1]) )
    return out_ar

How to initialize

Eg. create a list of points

# following initialisations lead to the same array of points (note the convert)
p=[P(0,0),P(0,1),P(-0.866025,-0.5),P(0.866025,0.5)]
q=convert( [[0,0],[0,1],[-0.866025,-0.5],[0.866025,0.5]] )  
r=convert( [(0,0),(0,1),(-0.866025,-0.5),(0.866025,0.5)] )

print type(p), ' | ' , p[2].x, p[2].y,  ' | ', p[2]
print type(q), ' | ' , q[2].x, q[2].y,  ' | ', q[2]
print type(r), ' | ' , r[2].x, r[2].y,  ' | ', r[2]

Output:

<type 'list'>  |  -0.866025 -0.5  |  x:-0.866025 y:-0.5
<type 'list'>  |  -0.866025 -0.5  |  x:-0.866025 y:-0.5
<type 'list'>  |  -0.866025 -0.5  |  x:-0.866025 y:-0.5

How to use

eg. Calculate the angle between :

  • the horizontal line through the first point
  • and the line through the two points

Then convert the result from radians to degrees: (watchout: won't work for dx==0)

print math.atan( ( p[3].y - p[0].y ) / ( p[3].x - p[0].x ) ) * 180.0/math.pi

Output:

30.0000115676
 
Notes by Willem Moors. Generated on momo:/home/willem/sync/20151223_datamungingninja/pythonbook at 2019-07-31 19:22