为什么这个对象没有赋值?

2024-09-29 19:29:09 发布

您现在位置:Python中文网/ 问答频道 /正文

Trie是节点列表:

class node:
    def __init__(self, parent, daughters, edge):
        self.parent = parent
        self.daughters = daughters
        self.edge = edge
        trie.append(self)
        self.index = len(trie) - 1

def TrieConstruction(patterns):
    global trie
    for node in trie:
        print('Node: ', node.parent, node.daughters, node.edge, node.index)
    trie.append(node(0, [], 0))
    ...

程序会给出以下错误:

File "trieMatching.1.py", line 22, in TrieConstruction
    trie.append(node(0, [], 0))
UnboundLocalError: local variable 'node' referenced before assignment

我不知道为什么这个变量会被取消赋值;难道函数不明白node是一个类,我正在实例化它吗?你知道吗


Tags: inselfnode列表index节点defclass
1条回答
网友
1楼 · 发布于 2024-09-29 19:29:09

您正在为类和for循环目标使用名称node

class node:
    # ...

for node in trie:
    # ...
trie.append(node(0, [], 0))

如果trie为空,则node将在函数中保持未绑定状态,因为没有可分配的值。你知道吗

你得重新命名其中一个。我建议您遵循Python style guide并使用CamelCase作为类名:

class Node:

小写字母\u加下划线表示您的函数(以及更好地反映职责的名称):

def construct_trie(patterns):

相关问题 更多 >

    热门问题