Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function within class?

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)
        ...
like image 346
Steven Avatar asked Apr 11 '11 00:04

Steven


People also ask

How do you access a function inside a class in Python?

Accessing the method of a class To access the method of a class, we need to instantiate a class into an object. Then we can access the method as an instance method of the class as shown in the program below. Here through the self parameter, instance methods can access attributes and other methods on the same object.

Can I call method inside class?

Instance methods are built functions into the class definition of an object and require an instance of that class to be called. To call the method, you need to qualify function with self. . For example, in a class that contains functions first() and second(), first() can call second().


2 Answers

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

def isNear(self, p):
    self.distToPoint(p)
    ...
like image 99
Jeff Mercado Avatar answered Sep 25 '22 22:09

Jeff Mercado


That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p). You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p).

like image 42
Aleksi Torhamo Avatar answered Sep 28 '22 22:09

Aleksi Torhamo