python - 如何将对象追加到实例变量列表中?

标签 python list object hash graph

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

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 相邻的点列表.

可能的解决方法:

  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_points ,将其存储在 scheme.adjacent_points[p]

关于python - 如何将对象追加到实例变量列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33836647/

相关文章:

python - 更新 View 上的查询集而不实际更新数据库

c - 我如何指向另一个指针然后增加第一个指针的值而不更改第二个指针的值

javascript - 在显示或隐藏时对齐列表

html - CSS 表格和列表样式位置错误?解决方法?

c++ - 在 C++ 中初始化为自身的对象

python - 在 Python 中创建列表内的列表

python - <> 在 Python 中是什么意思

javascript - 什么时候构造 Javascript 中的对象?

javascript - 使用事件监听器调用服务

python - 编码错误: 'QuerySet' object has no attribute '_prefetch_related_lookups'