实现一个表示 2D 点的类(即具有 x 和 y 位置的点) 实现以下方法: distanceFromOrigin():计算并返回到 Point2D(0,0) 的距离。
#this code
#p = Point2D(3,4)
#print(p.distanceFromOrigin())
#shall produce the following output
#5.0
import math
class Point2D:
def disctanceFromOrigin():
dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
return dist
p = Point2D(3,4)
print(p.distanceFromOrigin())
有人可以告诉我为什么这不起作用吗? 它给我返回一个类型错误:object() 不带参数
import math
class Point2D:
def __init__(self, x, y):
self.x = x
self.y = y
def disctanceFromOrigin(self):
origin = Point2D(0, 0)
dist = self.distanceFromPoint(self, origin)
return dist
def distanceFromPoint(self, point):
return math.sqrt((self.x - point.x)**2 + (self.y - point.y)**2
p = Point2D(3,4)
print(p.distanceFromOrigin())
当输入中的 distabceFromPoint 方法没有 self 时,在方法 distanceFromOrigin 中哟