1

我在一个类中嵌入了以下代码。每当我运行 distToPoint 时,它都会给出错误“unsupported operand type(s) for -: 'NoneType' and '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)) 
4

2 回答 2

1

您应该检查要发送给函数的值,p以便它具有浮点数。xy

旧帖子(三思而后行,我认为您并没有尝试使用distToPoint这种方式):

distToPoint不返回值,这可能是问题所在。

于 2011-04-11T00:45:29.273 回答
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
于 2011-04-11T00:56:11.590 回答