June 2015
Intermediate to advanced
298 pages
7h 15m
English
The Point class definition in the previous section included only two special methods. We'll now add a third method that's not special. Here's the third method for this class:
def dist(self, point):
return math.hypot(self.x-point.x, self.y-point.y)This method function accepts a single parameter, named point. The body of this method function uses math.hypot() to compute the direct distance between two points on the same plane.
Here's how we can use this function:
>>> p_1 = Point(22, 7) >>> p_2 = Point(20, 5) >>> round(p_1.dist(p_2),4) 2.8284
We've created two Point objects. When the p_1.dist(p_2) expression is evaluated, the object that was assigned to the p_1 variable will be assigned to the self variable. This ...
Read now
Unlock full access