[Tutor] line class

Alan Gauld alan.gauld at btinternet.com
Tue Jul 8 10:01:18 CEST 2008


"Christopher Spears" <cspears2002 at yahoo.com> wrote

> class Point(object):
>    def __init__(self, x=0.0,y=0.0):

> class Line(object):
>    def __init__(self, p1, p2):
>        self.p1 = Point(x1,y1)
> self.p2 = Point(x2,y2)

This is wrong I suspect.

You are passing two point objects into the constructor but
never using them. Instead you use the global variables
x1, etc to initialise the line. This means that all lines
will be the same!

I suspect it should be:

def __init__(self,p1,p2):
    self.p1 = p1
    self.p2 = p2

And since a line should not have zero length (although
you might argue with that!) you could also check if
p1==p2

def __init__(self,p1,p2):
     if p1 == p2:
         raise ValueError, "Line cannot have zero length"
    self.p1 = p1
    self.p2 = p2


> if __name__ == '__main__':
>    print "Creating a Line"
>
>    x1 = raw_input("Enter a x1 value: ")
>    y1 = raw_input("Enter a y1 value: ")
>    p1 = Point(x1,y1)
>    #print p1
>
>    x2 = raw_input("Enter a x2 value: ")
>    y2 = raw_input("Enter a y2 value: ")
>    p2 = Point(x2,y2)
>    #print p2
>
>    line = Line(p1,p2)

So although you pass p1,p2, here they are redundant
because you are using x,y above directly.



> Enter a x1 value: 0
> Enter a y1 value: 0
> Enter a x2 value: 0
> Enter a y2 value: 1
> Traceback (most recent call last):
>  File "line.py", line 79, in ?
>    line_slope = line.slope()
>  File "line.py", line 42, in slope
>    line_slope = dist_y/dist_x
> ZeroDivisionError: float division
>
> Basically, if the two the x values are the same, I will get a 
> ZeroDivisionError.
> A line in this case would simply point straight up.  What would 
> slope be
> in this case?

It would be infinite which most programming languages, including
Python, cannot represent. So you need to trap the error and report
the problem or return some arbitrary infinity flag.

HTH,

Alan G.




More information about the Tutor mailing list