Python 实现一个用于表示linestring的类,并实现一个方法length(),该方法返回(任意数量)或段的长度之和
我实现了一个类来定义一个LineString(对象)。LineString可以接受表示不同线段的任意数量的点。我需要计算每个线段的长度,并将它们加在一起,得到字符串的总长度。我看不出我的代码哪里出错了,因为我无法通过断言来测试我的长度函数是否工作 我曾尝试创建一个变量,而不是一个列表来计算每条线段的长度之和,但它仍然不起作用Python 实现一个用于表示linestring的类,并实现一个方法length(),该方法返回(任意数量)或段的长度之和,python,gis,Python,Gis,我实现了一个类来定义一个LineString(对象)。LineString可以接受表示不同线段的任意数量的点。我需要计算每个线段的长度,并将它们加在一起,得到字符串的总长度。我看不出我的代码哪里出错了,因为我无法通过断言来测试我的长度函数是否工作 我曾尝试创建一个变量,而不是一个列表来计算每条线段的长度之和,但它仍然不起作用 from math import sqrt class Point(object): def __init__(self, x, y): self
from math import sqrt
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, i, j):
self.x = self.x + i
self.y = self.y + j
class LineString(object):
def __init__(self, *coordinates):
self.coords = [Point(*p) for p in coordinates]
self.lengths = []
def __getitem__(self, key):
if type(key) == tuple:
return self.coords[key[0]][key[1]]
else:
return self.coords[key]
def move(self, delta_x, delta_y):
for self in self.coords:
self.move(delta_x, delta_y)
def length(self):
# base formula: length = sqrt((x2 - x1)**2 + (y2 - y1)**2)
points_temp = self.coords
for i in range(len(points_temp) - 1):
length = sqrt(((self.coords[i + 1].x - self.coords[i].x) ** 2) + (
(self.coords[i + 1].y - self.coords[i].y) ** 2))
self.lengths.append(length)
return sum(self.lengths)
if __name__ == '__main__':
# Tests for LineString
# ===================================
lin1 = LineString((1, 1), (0, 2)) # lin1 is an instance of LineString
assert lin1.length() == sqrt(2.0)
lin1.move(-1, -1) # Move by -1 and -1 for x and y respectively
print(lin1)
assert lin1[0].y == 0 # Inspect the y value of the start point.
# Implement this by overloading __getitem__(self, key) in your class.
lin2 = LineString((1, 1), (1, 2), (2, 2))
assert lin2.length() == 2.0
lin2.move(-1, -1) # Move by -1 and -1 for x and y respectively
assert lin2.length() == 2.0
assert lin2[-1].x == 1 # Inspect the x value of the end point.
print('Success! Line tests passed!')
我一直在使用倒数第二个断言时出错。首先,我建议使用Python的单元测试框架, 这样,您将使用
self.assertEqual(lin2.length(),2.0)
,而不只是说“在倒数第二个断言中出现错误”,它不仅会打印出错误,还会打印出lin2.length()
的实际值
第二,永远不要比较相等的双值-它们不精确,微小的错误可能会导致计算稍微偏离,从而导致相等失败。使用AssertalPosteQual代替-
但这不是问题所在。查找错误的最简单方法是以交互方式使用Python。只需在交互式shell中运行:
lin2 = LineString((1, 1), (1, 2), (2, 2))
lin2.length()
2.0
lin2.length()
4.0
这里有一个问题-length()函数没有清除self.length
字段,并且它会随着每次计算而不断增长