Using instance variables and methods

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 ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.