创建代表二维点的 class
Creating a class that represents 2D-points
实现一个 class 表示 2D 点(即具有 x 和 y 位置的点)实现以下方法:
distanceFromOrigin():计算并 returns 到 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())
有人能告诉我为什么这不起作用吗?
它返回一个 TypeError: object() takes no parameters
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())
实现一个 class 表示 2D 点(即具有 x 和 y 位置的点)实现以下方法: distanceFromOrigin():计算并 returns 到 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())
有人能告诉我为什么这不起作用吗? 它返回一个 TypeError: object() takes no parameters
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())