Newbie to python-- problem on Object Oriented Programming

Viewed 71

I worked on using the slope and the distance formula here. But I think indexing is the wrong approach, or is it?

class Line():
    def __init__(self,coord1,coord2):
        self.coord1 = coord1
        self.coord2 = coord2

    def distance(self):
        return ((coord2[0]-coord1[0])**2 + (coord2[1]-coord1[1])**2)**0.5

    def slope(self):
        return (coord2[1] - coord1[1])/(coord2[0]-coord1[0])
3 Answers

To access the class specific variables you need to use self.#varibale name So your functions should look like this:

    def distance(self):
        return ((self.coord2[0]-self.coord1[0])**2 + (self.coord2[1]-self.coord1[1])**2)**0.5

    def slope(self):
        return (self.coord2[1] - self.coord1[1])/(self.coord2[0]-self.coord1[0])

Assuming coord is a tuple I prefer to unpack them first for readability:

def slope(self):
    x1,y1 = self.coord1
    x2,y2 = self.coord2
    return (y2 - y1)/(x2-x1)

There's nothing wrong with indexing. You might find it more readable if you provide more descriptive names for the components. For example,

def distance(self):
    c1x = self.coord1[0]
    c1y = self.coord1[1]
    c2x = self.coord2[0]
    c2y = self.coord2[1]

    return ((c2x - c1x)**2 + (c2y - c1y)**2)**0.5

which you can make less verbose with tuple unpacking:

def distance(self):
    c1x, c1y = self.coord1
    c2x, c2y = self.coord2

    return ((c2x - c1x)**2 + (c2y - c1y)**2)**0.5

and even less verbose by working on the complex plane:

def distance(self):
    return abs(complex(**self.coord2) - complex(**self.coord1))

(For slope, the complex-number trick involves converting the difference between the two to polar coordinates with cmath.polar.)

Related