Adding to object in list ends up adding to all list objects

56 Views Asked by At

I'm new in Python and I want to make Dijkstra's algorithm and I'm having problem in the very beginning.

I have objects for vertices and edges:

class Vertex:
minDistance = float('inf')
previousVertex = None
edges = []
id = None
name = None

def __init__(self, id, name):
    self.id = id
    self.name = name


class Edge:
source = None
target = None
weight = None

def __init__(self, source, target, weight):
    self.source = source
    self.target = target
    self.weight = weight

I want to take a vertex and to his property edges add every edge that starts in it. Do this for every vertex I have:

vertices = []    

def createGraph(self, vertices, edgesToVertices):
    self.vertices = vertices[:]
    for x in vertices:
        for edge in edgesToVertices:
            if edge.source is x.id:
                x.edges.append(edge)

The problem is when I append the on the last line, the edge is added to ALL vertices in the list. Can someone please explain what am I doing wrong and why?

1

There are 1 best solutions below

1
On BEST ANSWER

The list, edges, that you defined in Vertex is a class variable. So, if you modify it, it affects all Vertex instances (hence the behavior that you're describing).

What you can do is:

class Vertex:
    def __init__(self, id, name):
        self.id = id
        self.name = name
        self.edges = []
        self.previousVertex = None
        self.minDistance = float('inf')

class Edge:
    def __init__(self, source, target, weight):
        self.source = source
        self.target = target
        self.weight = weight

This way, edges belongs to each instance.

By the way, I'm guessing that you intend createGraph() to be part of Edge. If that were the case, you could implement it like the following:

class Edge:
    def __init__(self, source, target, weight):
        self.source = source
        self.target = target
        self.weight = weight

    def createGraph(self, vertices, edgesToVertices):
        for vertex in vertices:
            for edge in edgesToVertices:
                if edge.source is vertex.id:
                    vertex.edges.append(edge)