类中的Python调用函数

Ste*_*ven 204 python class function call

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

但是如何在函数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)
        ...
Run Code Online (Sandbox Code Playgroud)

Jef*_*ado 346

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

def isNear(self, p):
    self.distToPoint(p)
    ...
Run Code Online (Sandbox Code Playgroud)

  • 如果我们不使用 self 会发生什么?并直接调用distToPoint(p)? (3认同)
  • 但是要小心self.foo()将使用方法解析顺序,该顺序可能会解析为其他类中的函数。 (2认同)
  • @Marlon Abeykoon的“自我”论点将丢失 (2认同)

Ale*_*amo 40

这不起作用,因为distToPoint在你的类中,所以如果你想引用它,你需要在它前面加上它,如下所示:classname.distToPoint(self, p).不过,你不应该这样做.更好的方法是直接通过类实例(类方法的第一个参数)引用该方法,如下所示:self.distToPoint(p).

  • @Yugmorf:只有一种情况应该使用`classname.distToPoint(self, p)`:当你定义一个覆盖`distToPoint`的子类时,但需要调用原始类。在这种情况下,如果您尝试像往常一样调用 `self.distToPoint(p)`,您最终会调用您刚刚定义的方法,并进入无限递归。如果不在类内,也只有一种情况你会使用`classname.distToPoint(obj, p)` 而不是`obj.distToPoint(p)`:如果obj 可能是子类的一个实例,但你需要调用定义的原始`distToPoint` *(续)* (2认同)