Python 减去浮点数

发布于 2024-10-31 11:57:10 字数 375 浏览 6 评论 0原文

我将以下代码嵌入到类中。每当我运行 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)) 

I have the following code embeded in a class.Whenever I run distToPoint it gives the error 'unsupported operand type(s) for -: 'NoneType' and 'float'' I don't know why it's returning with NoneType and how do I get the subtraction to work?

Both self and p are supposed to be pairs.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

戏剧牡丹亭 2024-11-07 11:57:10

为了比较,

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

For sake of comparison,

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)

returns

5.0
情归归情 2024-11-07 11:57:10

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

旧帖子(再想一想,我认为您没有尝试以这种方式使用 distToPoint):

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

You should check what value of p you are sending to the function, so that it has an x and y that are floats.

Old post (on second thought, I don't think you were trying to use distToPoint this way):

distToPoint doesn't return a value, this is probably the problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文