Python中如何减去浮点数

1 投票
2 回答
1370 浏览
提问于 2025-04-16 15:27

我在一个类里面有以下代码。每次我运行 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)) 

2 个回答

1

你需要检查一下你传给这个函数的 p 的值,确保它有 xy 这两个是浮点数的值。

之前的帖子(再想想,我觉得你可能不是想这样使用 distToPoint):

distToPoint 并没有返回任何值,这可能就是问题所在。

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

撰写回答