我在类中嵌入了以下代码。每当我运行distToPoint时,它会给出错误'不支持的操作数类型 - :'NoneType'和'float''我不知道为什么它返回NoneType和如何让减法工作?
self和p都应该是成对的。
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def distToPoint(self,p):
self.ax = self.x - p.x
self.ay = self.y - p.y
self.ac = math.sqrt(pow(self.ax,2)+pow(self.ay,2))
答案 0 :(得分:1)
您应该检查要发送给该函数的p
的值,以便它具有x
和y
浮点数。
旧帖(第二个想法,我不认为你试图以这种方式使用distToPoint
):
distToPoint
没有返回值,这可能是问题所在。
答案 1 :(得分:1)
为了便于比较,
import math
class Point(object):
def __init__(self, x, y):
self.x = x + 0.
self.y = y + 0.
def distToPoint(self, p):
dx = self.x - p.x
dy = self.y - p.y
return math.sqrt(dx*dx + dy*dy)
a = Point(0, 0)
b = Point(3, 4)
print a.distToPoint(b)
返回
5.0