自定义对象类型(networkx 图形类型 bool 表达式)的正确 python bool 表达式是什么?

what is the correct python bool expression for a custom object type (networkx graph type bool expression)?

我需要检查 networkx (nx) 图是否是有向图。例如,

In [70]: g = nx.DiGraph([(0,1), (2,0)])

In [71]: type(g)
Out[71]: networkx.classes.digraph.DiGraph

In [72]: type(g) == 'networkx.classes.digraph.DiGraph'
Out[72]: False

所以问题是我应该在行[72] 的右侧放置什么才能使其正常工作?显然我可以做一个不同的布尔值,例如 'digraph.DiGraph' in str(type(g)) 但这有点绕过更普遍的问题 "how to check a custom type is what you need it to be with a boolean?"

使用isinstance函数:

isinstance(g, networkx.classes.digraph.DiGraph)

所以,从根本上说,你遇到的困惑是因为 type(g) 是一个 type 对象,即 class 对象,但是 'networkx.classes.digraph.DiGraph' 是一个 字符串 ,而 type 对象不等于字符串。相反,您可以使用:

type(g) == nx.DiGraph

虽然通常您会看到:

type(g) is nx.DiGraph

但是如果你想包含 subclasses 你需要 instanceof:

instanceof(g, nx.DiGraph)