Why is `c.distance(origin)` the very same call as `Coordinate.distance(c, origin)`, and what binds `self` in each form?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
The Coordinate class from the video is given, along with two objects: point, sitting at (9, 12), and origin, sitting at (0, 0).
Assign to distance_to_origin the distance from point out to origin, obtained by calling the class's own distance method on point.
class Coordinate(object):
""" A coordinate made up of an x and y numerical value """
def __init__(self, xval, yval):
""" Sets the x and y values """
self.x = xval
self.y = yval
def getX(self):
""" Returns how far away self is on the x axis """
return self.x
def getY(self):
""" Returns how far away self is on the y axis """
return self.y
def distance(self, other):
""" Returns the euclidean distance between two Coordinate objects """
x_diff_sq = (self.x - other.x)**2
y_diff_sq = (self.y - other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
point = Coordinate(9, 12)
origin = Coordinate(0, 0)The distance method body
Copy getX, getY and distance from the class, write the Pythagoras body squaring self.x - other.x and self.y - other.y and raising the sum to 0.5, and note nothing enforces the type of other.
Calling a method with the dot operator
Trace c.distance(origin) with c taken as self and origin as other, and record the identical notation in my_list.append(3) and my_list.sort().
Coordinate.distance(c, origin) with self passed by hand
Write the three equivalent calls from the video and record that putting the class name before the dot requires the full parameter list, self included.