【发布时间】:2014-06-03 14:47:31
【问题描述】:
这些是我得到的指示:
创建一个由有序对 (x, y) 组成的 Point 类,表示点在 x 和 y 轴上的位置。构造函数允许传入 x 和 y 值,并且默认缺失值应为 0。您必须重写 str 方法才能正常打印该点(即“(2, 5)”) .
另外,创建一个由一对 Point 对象 p 和 q 组成的 Line 类。一条线可以通过以下两种方式之一进行实例化。
somePoint = Point(2, 3)
anotherPoint = Point(4, 8)
someLine = Line(somePoint, anotherPoint)
或者...
someLine = Line()
在第二种情况下,构造函数应该将两个点都初始化为原点(0, 0)。您必须重写 __str__ 方法以按如下方式打印该行:(2, 5)--(4, 7)。您的类还必须提供一个长度方法,该方法返回
段的长度。
这是模块文件
import final
somePoint = final.Point(4, 5)
anotherPoint = final.Point(5, 7)
someList = final.Line(somePoint, anotherPoint)
distance = final.Line.distance(someList)
到目前为止我的代码
import math
class Point():
def __init__(self, x, y):
self.xy = [x, y]
self.printer = ("(" + str(x) + "," + str(y) + ")")
def __str__(self):
return str(self.printer)
class Line():
def __init__(self, p, q):
self.coor = [p, q]
self.pq = (str(p) + "--" + str(q)) #<--------- From here down is where I'm having trouble.
def distance(self):
self.x1 = self.coor[0][0]
self.x2 = self.coor[1][0]
self.y1 = self.coor[0][1]
self.y2 = self.coor[1][1]
self.xdiff = math.fabs(int(self.x1) - int(self.x2))
self.ydiff = math.fabs(int(self.y1) - int(self.y2))
self.xsq = (self.xdiff ** 2)
self.ysq = (self.ydiff ** 2)
self.distance = float(math.sqrt(self.xsq + self.ysq))
def __str__(self):
return str(self.pq) + "the distance of that line is " + str(self.distance)
【问题讨论】:
标签: class oop python-2.7