NameError:未定义名称“distancepoint”

NameError: name 'distancepoint' is not defined

提问人:Annie 提问时间:10/16/2023 最后编辑:SeonAnnie 更新时间:10/16/2023 访问量:43

问:

import math
class point:
    def __init__(self,p1,p2):
        self.p1 = p1
        self.p2 = p2
    def distancepoint(self):
        x1,y1 = self.p1
        x2,y2 = self.p2
        distance = math.sqrt((x1-x2)**2 + (y1-y2)**2)
        return distance
p1 = point(2,4)
p2 = point(1,6)

distance = distancepoint(p1,p2)
print (f'Distance between 2 points: {distance}')

我是Python初学者。我不知道如何解决这个问题。

Python

评论

0赞 Abdul Aziz Barkat 10/16/2023
这回答了你的问题吗?Python3 NameError:未为定义的@staticmethod定义名称“method”(除了作为方法的明显点,并且在代码中是 和 的对象是整数。 会给你一个错误)distancepointp1p2pointself.p1self.p2x1,y1 = self.p1

答:

0赞 Swifty 10/16/2023 #1

你似乎对你的变量感到困惑:在点类定义中,p1 和 p2 是点坐标,distancepoint 是一个类方法,而后面的 p1 和 p2 是点,你尝试使用 distancepoint 作为函数(在类之外);以下是您可能想做的事情:

import math
class point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def distancepoint(self, other):
        distance = math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2)
        return distance
p1 = point(2,4)
p2 = point(1,6)

distance = p1.distancepoint(p2)
print (f'Distance between 2 points: {distance}')

# Distance between 2 points: 2.23606797749979
0赞 umair mehmood 10/16/2023 #2

通过查看代码,您似乎正在尝试编写一个程序来获取两点之间的距离,如果我是正确的,请尝试此代码。

你的代码实际上调用了一个方法,该方法是一个类方法,而你调用它时没有一个不可调用的对象。

import math

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def distance_to(self, other_point):
        return math.sqrt((self.x - other_point.x)**2 + (self.y - other_point.y)**2)

p1 = Point(2, 4)
p2 = Point(1, 6)

distance = p1.distance_to(p2)
print(f'Distance between 2 points: {distance}')

0赞 Seon 10/16/2023 #3

您在这里有两个选择:

  • 代码的编写方式应该是一个常规函数(在类之外),它接受两个点对象作为输入并返回距离:distancepoint
import math


class Point: # python devs usually use CamelCase for class names
    def __init__(self, x, y): # x and y, because we have two coordinates, not two points
        self.x = x 
        self.y = y


def distancepoint(p1, p2):
    x1, y1 = p1.x, p1.y
    x2, y2 = p2.x, p2.y

    distance = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
    return distance



p1 = Point(2, 4)
p2 = Point(1, 6)

distance = distancepoint(p1, p2)
print(f"Distance between 2 points: {distance}")
  • 另一种方法,你似乎瞄准了它,是定义为类的方法。这意味着您可以测量距离 从一个给定的对象到另一个 .distancepointPointPointPoint
class Point: # python devs usually use CamelCase for class names
    def __init__(self, x, y): # x and y, because we have two coordinates, not two points
        self.x = x 
        self.y = y


    def distance(self, other_p):
        x1, y1 = self.x, self.y
        x2, y2 = other_p.x, other_p.y

        distance = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
        return distance

p1 = Point(2, 4)
p2 = Point(1, 6)

distance = p1.distance(p2)
print(f"Distance between 2 points: {distance}")