我正在为这个简单的任务而苦苦挣扎。我需要创建 2 个类,Point 和 Route。我需要在路线中添加/删除点,然后计算路线中点之间的总距离。
到目前为止,我的代码是这样的:
import math
class Point:
"Two-dimensional points"
def __init__(self, x=0.0, y=0.0):
self._x = x
self._y = y
def __str__(self):
result = "\n".join(["x: %f" % self.x(),
"y: %f" % self.y(),
"rho: %f" % self.rho(),
"theta: %f" % self.theta()])
return result
# Queries
def x(self):
"Abscissa"
return self._x
def y(self):
"Ordinate"
return self._y
def rho(self):
"Distance to origin (0, 0)"
return math.sqrt(self.x()**2 + self.y()**2)
def theta(self):
"Angle to horizontal axis"
return math.atan2(self.y(), self.x())
def distance(self, other):
"Distance to other"
return self.vectorTo(other).rho()
def vectorTo(self, other):
"Returns the Point representing the vector from self to other Point"
return Point(other.x() - self.x(), other.y() - self.y())
# Commands
def translate(self, dx, dy):
"Move by dx horizontally, dy vertically"
self._x += dx
self._y += dy
def scale(self, factor):
"Scale by factor"
self._x *= factor
self._y *= factor
def centre_rotate(self, angle):
"Rotate around origin (0, 0) by angle"
temp_x = self.rho() * math.cos(self.theta() + angle)
temp_y = self.rho() * math.sin(self.theta() + angle)
self._x, self._y = temp_x, temp_y
def rotate(self, p, angle):
"Rotate around p by angle"
self.translate(-p.x(), -p.y())
self.centre_rotate(angle)
self.translate(p.x(), p.y())
class Route:
def __init__(self):
self.Point = []
def __add__ (x,y,index):
self.points.insert(Point(x,y), index)
Point 工作正常,但我不知道如何让 Route 工作。
我得到的错误是:
>>>
>>> route = Route()
>>> route.add(32, 12, 2)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
route.add(32, 12, 2)
File "C:\Users\John Wayne\Dropbox\kool\geom.py", line 73, in add
self.points.insert(Point(x, y), index)
TypeError: 'Point' object cannot be interpreted as an integer
>>>
好的,我已设法将 Route 类修复如下:
class Route:
def __init__(self):
self.points = []
def add_point(self, x, y, index):
self.points.insert(index, Point(x,y))
但现在我的方法 get_lenght 有问题:
def get_lenght(self, Point):
for Point in self.points:
这个 get_lenght 方法有什么问题?
非常感谢。