creating named instances of a class within a for loop -- related to networkx -- Python

StackOverflow https://stackoverflow.com/questions/22423626

  •  15-06-2023
  •  | 
  •  

Question

The problem I am facing is following:

Suppose we have some class ( not important what it does):

class Node: ...
    ...

What I need now is creating several instances of this class; all with names. I tried several things, here one try, which is obviously not working. just to make clear what I want to achieve:

for i in range(number_of_instances):
    "name"+str(i+1) = Node()

I need name for all of these objects to put them later on in a list. Actually it's the list containing all the nodes from a graph. The graph will be made with the networkx module. I need to be able to differentiate somehow between the nodes in the list. That's why I need the name.

my_graph = networkx.Graph()
for i in range(number_of_nodes):
    my_graph.add_node(Node(), name = str(i+1))

After executing this, my_graph.nodes() list somehow has mixed up the order of the nodes. So it does not correspond to order in which the nodes have been added to the graph. So I don't know anymore how to exactly differentiate between the nodes.

EDIT

Given the laplacian for the graph I set everything up and then draw the graph.

name_dict = nx.get_node_attributes(my_graph, "name")
pos = nx.spring_layout(my_graph)
nx.draw(my_graph, pos, with_labels=False)
nx.draw_networkx_labels(my_graph, pos, name_dict)
plt.show()

However this does not result in the correct labeling.

Was it helpful?

Solution

You don't need a name, you only need a reference. One simple solution is to put the reference in a dictionary:

node = {}
for i in range(number_of_instances):
    node[i] = Node()
...
for i in range(number_of_nodes):
    my_graph.add_node(node[i], name="node %s" % i)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top