Python call function within class

こ雲淡風輕ζ 提交于 2019-11-25 22:35:30

问题


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

回答1:


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

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



回答2:


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



来源:https://stackoverflow.com/questions/5615648/python-call-function-within-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!