类中的Python调用函数

问题:类中的Python调用函数

我有这段代码可以计算两个坐标之间的距离。这两个函数都在同一类中。

但是,如何在函数distToPoint中调用该函数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)
        ...

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

回答 0

由于这些是成员函数,因此在实例上将其称为成员函数self

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

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

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

回答 1

那是行不通的,因为distToPoint它在您的类内部,因此如果要引用它,则需要在类名前面加上前缀,例如:classname.distToPoint(self, p)。但是,您不应该那样做。更好的方法是直接通过类实例(这是类方法的第一个参数)引用该方法,如下所示:self.distToPoint(p)

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