首页 > 解决方案 > Python:为什么会出现“意外的关键字参数”错误?

问题描述

我正在尝试设置图表。对于初始化,我想要选择是否从节点和边的集合开始。所以我给了他们默认值None。或者我是这么想的:

def Graph():
    def __init__(self, nodes=None, edges=None, msg="test"):
        """
        assumes that the node and edge lists are the respective objects
        """
        if nodes == None:
            self.nodes = []
        else:
            self.nodes = nodes
            
        if edges == None:
            self.edges = []
        else:
            self.edges = edges
        
        self.node_names = []
        for node in nodes:
            self.node_names.append(node.get_name())
            
        self.msg = msg

(味精部分是用最简单的例子测试代码)

我得到的是:

g = Graph(msg="33")
Traceback (most recent call last):

  File "<ipython-input-29-cc459c9baef3>", line 1, in <module>
    g = Graph(msg="33")

TypeError: Graph() got an unexpected keyword argument 'msg'

有谁能够帮我?这可能是一件简单得可笑的事情,但我只是没有看到它,而且我在这里有点生气......

标签: pythonconstructorkeyword-argument

解决方案


您没有将其定义Graph为类,而是定义为常规函数。

替换def Graph():class Graph:


推荐阅读