繁体   English   中英

如何将对象追加到作为实例变量的列表中?

[英]How to append objects to the list that is an instance variable?

我的程序有一个方案,其连接线由两点决定。 我想创建某种图形并在方案初始化时获取每个点的相邻点。

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)]

但是它只有一个。 为什么?

但是它只有一个。 为什么?

由于Point(1, 0) is Point(1, 0)返回false,因此与1, 0相邻的点有两个单独的列表。

可能的解决方法:

  1. 重用同一点对象:

     p01 = Point(0,1) some_list = [ Line(Point(0,0), p01)) Line(p01, Point(0,2))) ] scheme = Scheme(some_list) 
  2. 实现__new__ ,并存储到目前为止找到的所有点的查找表,以使Point(1, 0) is Point(1, 0)返回true。

  3. 与其将数据存储在p.adjacent_pointsp.adjacent_points将其存储在scheme.adjacent_points[p]

问题在于,即使第一个列表中的Point(0,1)共享坐标,它们的实例也与第二个列表中的实例不同。 您使用了一个集合来构造point_list ,因此重复点将被过滤掉,但是您并没有以任何方式使用它来设置相邻点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM