我正在努力创建 rustworkx.PyGraph 类的子类,并且我遇到了一些奇怪的行为。也就是说,它不允许我将关键字争论传递给我的班级。
这是一个最小的例子:
import rustworkx
class Graph(rustworkx.PyGraph):
def __init__(self, multigraph=False):
super().__init__(multigraph=multigraph)
regular_graph = rustworkx.PyGraph(multigraph=False)
print(f"The first graph is a multigraph: {regular_graph.multigraph}")
try:
my_graph = Graph()
except Exception as e:
print(f"Error: {e}")
正在输出
The first graph is a multigraph: False
Error: object.__init__() takes exactly one argument (the instance to initialize)
我查看了 Python 中类定义的源代码,一切似乎都很好:
class PyGraph(Generic[_S, _T]):
attrs: Any
multigraph: bool = ...
def __init__(self, /, multigraph: bool = ...) -> None: ...
def add_edge(self, node_a: int, node_b: int, edge: _T, /) -> int: ...
我认为我可以通过在有机会添加任何边之前设置变量显式来解决这个问题,但这也不起作用:
import rustworkx
class Graph(rustworkx.PyGraph):
def __init__(self, multigraph=False):
super().__init__()
self.multigraph = multigraph
regular_graph = rustworkx.PyGraph(multigraph=False)
print(f"The first graph is a multigraph: {regular_graph.multigraph}")
try:
my_graph = Graph()
except Exception as e:
print(f"Error: {e}")
The first graph is a multigraph: False
Error: attribute 'multigraph' of 'rustworkx.PyGraph' objects is not writable
我不知道此时该怎么做,因此,如果您能帮助解释发生了什么以及如何解决它,我们将不胜感激。谢谢!
您没有查看实际的源代码。 实际源代码是用 Rust 编写的。您正在查看类型存根,它与实际实现不匹配。
PyGraph
实际上并没有定义 __init__
。他们使用的 Rust/Python 兼容层 PyO3 不支持这一点。它所做的支持是__new__
:
只能指定Python的
方法,__new__
不可用。__init__
因此,如果您定义
__new__
,至少应该解决此特定错误:
class Graph(rustworkx.PyGraph):
def __new__(cls, multigraph=False):
return super(Graph, cls).__new__(cls, multigraph=multigraph)