Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newbie to python-- problem on Object Oriented Programming

Tags:

python

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])
like image 220
Mourya Avatar asked Dec 10 '25 04:12

Mourya


2 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])
like image 106
Eumel Avatar answered Dec 11 '25 19:12

Eumel


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)
like image 44
JeffUK Avatar answered Dec 11 '25 19:12

JeffUK