类内的Python调用函数

2024-04-24 03:55:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但是,如何调用函数isNear中的函数distToPoint

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

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

Tags: to函数代码self距离usedeffind
2条回答

因为这些是成员函数,所以将其作为实例的成员函数调用,self

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

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

相关问题 更多 >