Frage

I have created an example graph like this:

class myObject(object):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

one = myObject("ONE")
Graph = nx.Graph()
Graph.add_node(one)

How can I access the attributes of the object "one" in this case? I figured out that if I add the object as attribute of the node I can access it, however accessing with

In [1]: Graph[one]
Out[1]: {}

or for example

In [2]: print Graph[one]
{}

to get the name printed does not work.

I also know that I could iterate over the list returned by

Graph.nodes()

but I was wondering if there is a better way to do this.

War es hilfreich?

Lösung

You can just inspect your object 'one'

In [1]: import networkx as nx

In [2]: %paste
class myObject(object):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

one = myObject("ONE")
Graph = nx.Graph()
Graph.add_node(one)

## -- End pasted text --

In [3]: print(one)
ONE

You can store arbitrary data with nodes in NetworkX by using node attributes. That might be simpler. You could even add a custom object as an attribute.

In [4]: G = nx.Graph()

In [5]: G.add_node("ONE", color='red')

In [6]: G.node["ONE"] # dictionary of attributes
Out[6]: {'color': 'red'}

In [7]: G.add_node("ONE",custom_object=one)

In [8]: G.node["ONE"] # dictionary of attributes
Out[8]: {'color': 'red', 'custom_object': <__main__.myObject at 0x988270c>}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top