-
Book Overview & Buying
-
Table Of Contents
Python Essentials
By :
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 is the instance of Point that's doing the relevant processing. The argument to the dist() method, assigned to the p_2 variable, will be assigned to the point parameter variable.
When we evaluate obj.method()...