Python 从点类到线字符串类
我创建了一个Point类,它将x,y坐标作为参数。此外,我还想创建一个Linestring类,该类接受用户想要的任意多个参数,并将它们存储为点。到目前为止:Python 从点类到线字符串类,python,line,point,Python,Line,Point,我创建了一个Point类,它将x,y坐标作为参数。此外,我还想创建一个Linestring类,该类接受用户想要的任意多个参数,并将它们存储为点。到目前为止: class Point(object): def __init__(self,x,y): self.x = x self.y = y def move(self,movex,movey): self.x += movex self.y += movey class LineString(objec
class Point(object):
def __init__(self,x,y):
self.x = x
self.y = y
def move(self,movex,movey):
self.x += movex
self.y += movey
class LineString(object):
def __init__(self, *args):
self.points = [Point(*p) for p in args]
现在我在self.points中存储了一个点列表。
问题是如何在linestring类中使用点的移动函数。
我试过类似的方法,但不起作用
def moveline(self,movex,movey):
self.points.move(movex,movey)
为了准确说明@MichaelButscher在评论中所说的内容,您的
moveline
函数的问题在于self.points
是点
对象的列表,而不是点
对象本身。因此,我们需要遍历此列表,并为每个点
对象调用move
函数。这可以通过for
循环来实现。更新后的moveline
函数可能如下所示:
def moveline(self,movex,movey):
for point in self.points:
point.move(movex,movey)
使用
for
-循环在每个点上迭代并移动它。