我的程序有一个由两点确定的连接线的方案。我想创建某种图形并在方案初始化时获取每个点的相邻点。
class Point(object):
def __init__(self,x,y):
self.adjacent_points=list()
self.x=x
self.y=y
def __key(self):
return (self.x, self.y)
def __hash__(self):
return hash(self.__key())
def __eq__(self, other):
return self.__key()==other.__key()
def __repr__(self):
return "Point(%s, %s)" % (self.x, self.y)
class Line(object):
def __init__(self, point_1, point_2):
self.point_1=point_1
self.point_2=point_2
class Scheme(object):
def __init__(self, element_list):
self.element_list =element_list
self.point_list=list()
self.get_adjacent_points()
def get_adjacent_points(self):
self.point_list = list(set(p for l in self.element_list for p in (l.point_1, l.point_2)))
for l in self.element_list:
l.point_1.adjacent_points.append(l.point_2)
l.point_2.adjacent_points.append(l.point_1)
我尝试用两条线和三个点制作简单的方案。
point_list=list()
some_list = list()
some_list.append(Line(Point(0,0), Point(0,1)))
some_list.append(Line(Point(0,1), Point(0,2)))
scheme = Scheme(some_list)
假设坐标为(0,1)的点有两个相邻点:
>>> print(scheme.point_list[0])
Point(0, 1)
>>> print(scheme.point_list[0].adjacent_points)
[Point(0, 0)]
但它只有一个。为什么?
最佳答案
But it has only one. Why?
因为Point(1, 0) is Point(1, 0)
返回 false,因此有两个单独的与 1, 0
相邻的点列表.
可能的解决方法:
重用相同的点对象:
p01 = Point(0,1) some_list = [ Line(Point(0,0), p01)) Line(p01, Point(0,2))) ] scheme = Scheme(some_list)
实现
__new__
,并存储迄今为止找到的所有点的查找表,以便Point(1, 0) is Point(1, 0)
返回 true。而不是将数据存储在
p.adjacent_points
,将其存储在scheme.adjacent_points[p]
关于python - 如何将对象追加到实例变量列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33836647/