NetworkX - Graph.nodes() 如何接收参数?

问题描述

当我在这里查看 Graph.nodes() 的代码时:https://github.com/networkx/networkx/blob/main/networkx/classes/graph.py#L658 它不接受任何参数。那么我怎么能传递像 data=True 这样的东西(例如,Graph.nodes(data=True))?理想情况下,我会收到“出现意外的关键字参数‘数据’”错误

它也被装饰为一个属性,但我可以将它称为一个函数。这可能是一个基本的python问题,但这是我第一次遇到这个问题。

解决方法

networkx 放在一边。拿这个代码片段。

class CallableIterable:
    def __init__(self,val):
        self.val = val[:]

    def __call__(self,arg1=True):
        print('acting as a callable')
        return f'You called this with {arg1}'

    def __contains__(self,arg):
        print('acting as an iterable')
        return arg in self.val

class Graph:
    @property
    def nodes(self):
        return CallableIterable([1,2,3,4,5])

您可以看到有两个类 CallableIterableGraphGraph 有一个属性 nodes,它在调用时返回 CallableIterable 的一个实例。

创建 Graph g 的实例。

g = Graph()

现在您可以通过两种方式使用属性 g.nodes

作为可迭代对象

print(1 in g.nodes)

这给了

acting as an iterable
True

这是因为 in 触发了 __contains__ 类的 CallableIterable 方法(在本例中)。

作为可调用对象

print(g.nodes('some random value'))

这给了

acting as a callable
You called this with some random value

这是因为它触发了 __call__ 类的 CallableIterable 方法。

() 中传递的参数,在这种情况下,'some random value'g.nodes('some random value') 或在您的情况下,data=TrueGraph().nodes(data=True) 被传递给 __call__ 属性的返回值 (which is g.nodes)NOT TO 属性修饰函数Graph.nodes

在内部这是 g.nodes.__call__('some random value')

根据这种理解,对 networkx 应用相同的原则,其中 NodeView 是返回的对象类型,而不是本示例中看到的 CallableIterable,工作原理相同。

  1. nodes = NodeView(self)NodeView class 的一个实例。
  2. 这个类有一个 __call__ 和一个 __contains__ 方法。
  3. 这让您可以将其用作可调用/函数 (Graph().nodes(data=True))) 并作为可迭代对象 ('something' in Graph().nodes)。

NodeView 类除了 __call____contains__ 之外还有其他函数,每个函数都会被适当调用。

这基本上就是文档字符串的含义

    Can be used as `G.nodes` for data lookup and for set-like operations.
    Can also be used as `G.nodes(data='color',default=None)` to return a
    NodeDataView which reports specific node data but no set operations