Frage

I am trying to implement a graph structure in python. The entire logic is bit weird, but I am facing a very specific issue.

t_graph = graph()

for i in range(0, 2):
    non_emitting_state = template_node(-1, -1, 1, emitting=True, next_level = i)
    t_graph.add_node(non_emitting_state)
    for j in range(0, 2):
        for k in range(0, 3):
            t_node = template_node(i, j, k)
            t_graph.add_node(t_node)

and my node objects are

class template_node:
    parents  = []
    children = []
    mu = []
    sigma = []
    emitting = False
    identifier = [0 for x in range(3)]

    def __init__(self, level_no, HMM_no, state_no, emitting = False, next_level = -1):
        if next_level == -1: next_level = level_no + 1

        self.identifier[0] = level_no
        self.identifier[1] = HMM_no
        self.identifier[2] = state_no

and the graph class is

class graph:
    template_nodes = []
    def add_node(self, template_node):
        self.template_nodes.append(template_node)

But after the loop when I check the identifiers, all are same, the one corresponding to the last iteration in the loop chain. i.e all the nodes have identifiers as [1,1,2], this means the every time a new node is being created, it is overriding the properties of the existing nodes.

I have tried t_graph.add_node(copy.deepcopy(t_node)) and still it is the same. Any idea on what I should do in order to avoid overriding of the fields.

War es hilfreich?

Lösung

identifier is a class variable, not specific for the instance. Move

parents  = []
children = []
mu = []
sigma = []
emitting = False
identifier = [0 for x in range(3)]

into __init__(). Also the same is recommended for a graph class as well.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top