0
class Line():
    
    def __init__(self, coor1 , coor2):
        
        self.coor1 = coor1 
        self.coor2 = coor2 
      
    
    def distance(self):
        
        for x1,y1 in self.coor1, x2,y2 in self.coor2:
                
                distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
        
        return distance

coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)

li.distance()

Hi, I am not too sure why (x2,y2) wasn't able to be defined while the first variable (x1,y1) was. I am not too sure how to include both tuples in the for loop, but shouldn't both be defined or none of them are defined? Thanks!

  • I'm surprised it's not a syntax error, I guess it raises the `NameError` that you get before it sees the second `in`. – Anentropic Jul 27 '23 at 08:42
  • if `coordinate1 = (3,2)` then you don't need a for loop at all, you just have a single tuple that you can unpack directly – Anentropic Jul 27 '23 at 08:44
  • you would use `for x1,y1 in self.coor1` if coor1 was e.g. a list of coordinate tuples, this does two things: it iterates over the list of tuples, and then it unpacks each tuple into the loop variables `x1` and `y1` – Anentropic Jul 27 '23 at 08:47
  • You might as well unpack the tuples in your constructor. That would make the code in your *distance()* function simpler and clearer – DarkKnight Jul 27 '23 at 09:11
  • @DarkKnight, but then every time a line is created, unnecessary code will run. I don't think that's a good advice. There is simply no reason for that. – Martynas Žiemys Jul 27 '23 at 09:52
  • @MartynasŽiemys If *distance()* is called multiple times for any any given instance of **Line** then unpacking in the constructor offers a performance benefit. Where you do the unpacking will depend on how the class is being used. My comment was about simplifying the code in the *distance()* function – DarkKnight Jul 27 '23 at 09:59
  • "Where you do the unpacking will depend on how the class is being used." :D I wouldn't do unpacking at all to be honest. – Martynas Žiemys Jul 27 '23 at 10:14

1 Answers1

3

You are not using the for loop correctly. You don't need a loop to assign multiple values at once. Just do:

class Line():
    
    def __init__(self, coor1 , coor2):
        self.coor1 = coor1 
        self.coor2 = coor2 
    
    def distance(self):
        x1,y1 = self.coor1 
        x2,y2 = self.coor2
        distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
        return distance

    
coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)

print(li.distance())

Since the tuples contain two values, they will be assigned to the 2 variables separated by the comma:

x,y = (1,2)

is same as

x = 1
y = 2

Or you could just:

return sum([(i[0] - i[1])**2 for i in zip(self.coor1, self.coor2)])**0.5

And that would work with n-dimensional vectors.