Search code examples
pythonnodesnetworkxundirected-graph

How to access attributes of a class instance which is a graph node via the graph?


Class definition:

class Blah:
    def __init__(self,x):
        self.x = x

Part of main(): (imported networkx)

G = networkx.Graph()
H = []

for i in range(1,5):
    H.append(Blah(i))

for i in H:
    G.add_node(i)

Now, if I want to print H[2].x using G then how do I do it?

G[2].x certainly wouldn't work. Will G(H[2]).x work?

Just asking for information. I can use H in my problem.


Solution

  • So if you define:

    class Blah:
        def __init__(self,x):
            self.x = x
    
    G = networkx.Graph()
    H = []
    
    for i in range(1,5):
        H.append(Blah(i))
    
    for i in H:
        G.add_node(i)
    

    Now you want to access the attributes of nodes of G. To do that, you need to use the networkx commands to access the nodes of G:

    for node in G:
        print(node.x)
    > 1
    > 2
    > 3
    > 4