Practice Problem “Object Oriented Python”, Page 3/8

Why can x and y be called on the “other” argument for the calculate_distance () method via other.x and other.y?

Is the x and y from other.x and other.y derived from the init?
If yes, why is it callable on “other” and not only on “self”?

import math

class Point2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def calculate_distance(self, other):
        return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2)
        
point1 = Point2D(3, 4)
point2 = Point2D(9, 5)
distance = point1.calculate_distance(point2)
print(distance)
1 Like

Because other is the parameter for the function calculate_distance and it takes the argument point2 when we call that function -

And point2 is an instance of the same Class Point2D. Therefore point2 will also have x and y attributes.

That’s why we are able to use other.x and other.y.

2 Likes

Thanks for your reply!

So in this setup

distance = point1.calculate_distance(point2)

self is intertwined with point1 and other with point2, however x and y are available for point1 and point2 because they are both instances of the Point2D.

2 Likes