子类 super().__init__(*args, **kwargs) 不起作用。说 object.__init__() 只接受一个参数(要初始化的实例),但它不接受

问题描述 投票:0回答:1

我正在努力创建 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

我不知道此时该怎么做,因此,如果您能帮助解释发生了什么以及如何解决它,我们将不胜感激。谢谢!

python-3.x class subclass init
1个回答
0
投票

您没有查看实际的源代码。 实际源代码是用 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)
© www.soinside.com 2019 - 2024. All rights reserved.