Fix Python – How can I call a function within a class?

Question

Asked By – Steven

I have this code which calculates the distance between two coordinates. The two functions are both within the same class.

However, how do I call the function distToPoint in the function isNear?

class Coordinates:
    def distToPoint(self, p):
        """
        Use pythagoras to find distance
        (a^2 = b^2 + c^2)
        """
        ...

    def isNear(self, p):
        distToPoint(self, p)
        ...

Now we will see solution for issue: How can I call a function within a class?


Answer

Since these are member functions, call it as a member function on the instance, self.

def isNear(self, p):
    self.distToPoint(p)
    ...

This question is answered By – Jeff Mercado

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0