如何将自定义Point类对象用作NetworkX节点?解决存储与访问问题
Fixing the add_node Error
First up, let's tackle that NetworkXError when you run G.add_node(0, p). The issue here is that NetworkX interprets the second positional argument as attr_dict, which requires a dictionary type. Passing your raw Point object directly violates this requirement, hence the error.
The fix is straightforward: use a keyword argument to store your Point object as a node attribute. You can pick any attribute name you like (I'll use point as an example):
G.add_node(0, point=p) # 'point' is a custom attribute name you can adjust
Accessing the Point Object & Its Methods
When you tried G[0].x and got an AttributeError, that's because G[0] returns the adjacency dictionary for node 0 (it stores neighbor nodes and edge attributes), not the node's own properties. To access node attributes, you need to use G.nodes[node_id]:
# Retrieve the Point object associated with node 0 my_point = G.nodes[0]['point'] # Now you can access attributes or call methods print(my_point.x) my_point.some_method(some_args)
For a slightly cleaner syntax, you can also use NetworkX's built-in attribute accessor:
my_point = G.nodes[0].get('point')
Using Point Objects Directly as Nodes (Hashable Class)
Since you've already added __hash__, __eq__, and other required methods to make your Point class hashable, you can use Point instances directly as node IDs:
# Create Point instances p1 = point(1, 2) p2 = point(3, 4) # Add them as nodes G.add_node(p1) G.add_node(p2) # Add an edge between them G.add_edge(p1, p2)
In this case, calling methods on the Point object is even simpler—you don't need to go through the graph at all, because the node itself is the Point instance:
p1.some_method(some_args)
If you specifically want to use integer IDs as nodes but still chain method calls like G[node_id].some_method(), you can wrap your graph in a simple custom class to streamline access:
class MyPointGraph(networkx.Graph): def node_point(self, node_id): return self.nodes[node_id]['point'] # Usage example G = MyPointGraph() G.add_node(0, point=point(0, 0)) G.node_point(0).some_method(some_args)
Alternatively, just use a short attribute name like p to keep access concise:
G.add_node(0, p=point(0, 0)) G.nodes[0]['p'].some_method(some_args)
Quick Recap
- Always use keyword arguments when attaching custom objects as node attributes (avoid positional arguments for this).
G[node_id]is for neighbor/edge data—node properties live inG.nodes[node_id].- If using Point instances as node IDs, call methods directly on the instance itself (no need to route through the graph unless you need additional node attributes).
内容的提问来源于stack exchange,提问作者Luka Petrović

