-1

The following code computes the distance and the slope between two coordinates. The tuple unpacking is perform directly in the functions .distance() and .slope(). I would like to perform the tuple unpacking directly in the __init__method. Do you have any idea how to do it? I tried with indexing but probably I did something wrong.

class Line(): #We define the variables (attributes of the class)    def __init__(self,coor1,coor2): self.coor1=coor1 self.coor2=coor2 #We define a function that unpack the tuples and calculates the distance between the points    def distance(self): x1,y1=self.coor1 x2,y2=self.coor2 return ((x2-x1)**2+(y2-y1)**2)**(1/2) #We define a function that unpack the tuples and calculate the slope def slope(self): x1,y1=self.coor1 x2,y2=self.coor2 return (y2-y1)/(x2-x1) 

2 Answers 2

1

You need to initialize (self.x1, self.y1) and (self.x2, self.y2) similar to how you defined self.coor1 and self.coor2 in your __init__. For example:

class Line(): def __init__(self,coor1,coor2): #self.coor1 = coor1 #self.coor2 = coor2 self.x1, self.y1 = coor1 self.x2, self.y2 = coor2 def distance(self): return ((self.x2-self.x1)**2+(self.y2-self.y1)**2)**(1/2) def slope(self): return (self.y2-self.y1)/(self.x2-self.x1) 
Sign up to request clarification or add additional context in comments.

Comments

0

you can use list unpacking for defining (x, y) cordinates value as

class Cord: def __init__(self, cord1, cord2): self.x1, self.y1 = cord1 self.x2, self.y2 = cord2 

Apart from this you can, create a class for points cordinates and the use that class object in the class Line for calculationn. Below is sample code

class Point: def __init__(self, x, y): self.x = x self.y = y class Line: def __int__(self, cord1, cord2): self.cord1 = cord1 self.cord2 = cord2 def distance(self): return ((self.cord1.x - self.cord2.x)**2 + (self.cord2.y - self.cord2.y)**2)**0.5 def slope(self): return (self.cord2.y-self.cord1.y)/(self.cord2.x - self.cord1.x) 

1 Comment

Thank you very much. You added the option to create a class for points coordinates. Really nice!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.