Object-Oriented Python Practice Problems

Screen - 3. 2D Points
https://app.dataquest.io/m/1000352/object-oriented-python-practice-problems/3/2-d-points

def calculate_distance(self, other):
dx = self.x - other.x
dy = self.y - other.y
return math.sqrt(dx * dx + dy * dy)

How are we using other.x and other.y here??

We have not mentioned those attributes anywhere in the class

1 Like

Please make sure that when you ask questions -

  1. Share the link to the Mission/Mission Step
  2. Try to apply the appropriate tags to the question if possible
  3. Properly format your code.

Whenever you try to create a new post, you are presented with a specific format based on which you can structure your question. I would suggest going through that format in more detail for any future questions.

You can also refer to Introducing guidelines for all technical questions in our Community and Guide: How to Ask a Good Question as well.

1 Like

Have you ever hard of this statement?

:bulb:
EVERYTHING IN PYTHON IS AN OBJECT

This means that every entity has some metadata (attributes) and associated functionality (methods). When we create an instance of a class (initialize), in this case the class is Point2D and name the instance point1 this will make point1 be an object (an object is an instance of a class).

point1 = Point2D(4,5)

So point1 is an instance of Point2D. We can create another instance of Point2D lets name it point2

point2 = Point2D(6,7)

since everything in python is an object we can also pass functions or instances of a class as arguments in a functions, that’s why we pass other in calculate_distance method and other is an instance of Point2D we can access other.y or other.x

point1 = Point2D(3, 4)
point2 = Point2D(9, 5)
distance = point1.calculate_distance(point2)
print(distance)

the above in long format

distance = Point2D(3,4).calculate_distance(other=Point2D(9,5))
print(distance)

The output will be the same

1 Like

With the screen link you have just provided, X and Y are parameters that have been defined in the special method i.e init__method.
i.e
def __init__(self, x, y):
self.x = x
self.y = y
So you don’t have to include them in the parenthesis of your method( def calculate_distance) . Other.x and other.y is just but away of accessing the attribute contain in x and y. Please you can use this for more clarification.

1 Like