我定义了一个图类,它具有一个函数,用于获取节点名称并将名称和节点添加到字典中。当我运行程序时,我在底部收到错误。为什么它认为我给了它两个论点?
class Graph:
def __init__(self):
self.node_list = {}
self.number = 0
def node(node_name):
if node_name in self.node_list.keys:
return node_list[node_name]
else:
node_list[node_name] = Node()
...
def PrefixTrieConstruction(patterns):
trie = Graph()
trie.node('root')
for pattern in patterns:
currentNode = trie.node('root')
for symbol in pattern:
for daughter in currentNode.daughters:
if daughter.label == symbol:
currentNode = daughter
break
else:
node_name = Trie.name_node()
Trie.node(node_name)
Trie.edge(currentNode, node_name, symbol)
currentNode = node_name
return Trie
Traceback (most recent call last):
File "PythonProject2.3.py", line 168, in <module>
main()
File "PythonProject2.3.py", line 163, in main
TrieMatching(text, PrefixTrieConstruction(patterns))
File "PythonProject2.3.py", line 68, in PrefixTrieConstruction
trie.node('root')
TypeError: node() takes 1 positional argument but 2 were given
您缺少self
:
def node(self,node_name):
self
指的是你正在调用方法的实例,所以你已经传递了这个实例,所以传递'root'
显然会给你看到的错误。
trie.node('root')
基本上是做Graph.node(trie,"root")
,所以你传递两个参数到一个方法,在你的方法中的node_name
被解释为实例,所以'root'
是一个额外的参数,除非你使用静态或类方法的第一个参数到你的方法应该始终是self
,它可以是任何名称,但几乎每个python程序员按照惯例使用self
来引用实例。
difference-between-class-and-instance-methods
what-is-the-difference-between-staticmethod-and-classmethod-in-python
what-is-the-purpose-of-self-in-python
这很简单!函数node
只接受一个参数,但是位于一个类中。给定隐式类实例和参数,这是2个参数。要解决这个问题,可以将函数编辑为
def node(self,node_name):
在python中,方法的第一个参数始终是调用该方法的对象。按照惯例,这个变量被称为self
,但没有规则规定必须如此。所以当你写:
def node(node_name):
node_name
被解释为"self"变量,该函数的预期用法是:
trie.node() #within this call, trie is bound to node_name
所以当你写:
trie.node('root')
trie
绑定到node_name
, 'root'
是一个额外的参数,导致错误。
self
变量:
def node(self, node_name):