Screen - 3. 2D 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
Please make sure that when you ask questions -
- Share the link to the Mission/Mission Step
- Try to apply the appropriate tags to the question if possible
- 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.
Have you ever hard of this statement?
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)
point1 is an instance of
Point2D. We can create another instance of
Point2D lets name it
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
calculate_distance method and
other is an instance of
Point2D we can access
point1 = Point2D(3, 4)
point2 = Point2D(9, 5)
distance = point1.calculate_distance(point2)
the above in long format
distance = Point2D(3,4).calculate_distance(other=Point2D(9,5))
The output will be the same
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.
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.