NameError:名称“ AnyName”未定义

时间:2019-08-13 21:53:13

标签: python python-3.x

我正在尝试根据链接列表和节点创建N-Ary树。但是每当我尝试向树中添加新值时,我都会不断得到:

NameError:名称“ self”未定义

我使用模块,因此必须从其他文件导入类。

我在树代码的 def addTree(self,value,parent = self.root):中遇到此错误

树代码

from Resources.LinkedList import *

class Tree:
def __init__(self):
    self.root = LinkedList()

def addTree(self, value, parent = self.root):
    parent.addLinkedList(value)

节点代码

from Resources.LinkedList import *

class Node:
    def __init__(self,name):
        self.name = name
        self.children = LinkedList()
        self.next = None

链接列表代码

from Resources.Node import *
from Resources.Compare import *

class LinkedList:
    def __init__(self):
        self.first = None

    def addLinkedList(self,value):
        if (not self.first):
            self.first = Node(value)
        else:
            compare = Compare()
            if(compare.compare(self.first,value)>0):
                stack = self.first
                self.first = Node(value)
                self.first.next = stack
                return True
            else:
                previous = self.first
                current = self.first.next

                while(current):
                    if (compare.compare(current,value)<0):
                        previous = current
                        current = current.next
                         return True
                    elif (compare.compare(current,value)>0):
                        stack = current
                        previous.next = Node(value)
                        previous.next.next = stack
                        return True
                    else:
                        previous.next = Node(value)
                        previous.next.next = current.next
                        return True

                previous.next = Node(value)
                return True

也感谢您的帮助,我是Python的新手,我不知道自己在做什么错。

1 个答案:

答案 0 :(得分:2)

问题在于“自我”仅在方法中定义,不能在参数中使用,在这种情况下,技巧是使用“无”作为参数并进行验证:

def addTree(self, value, parent = None):
    if parent is None:
        parent = self.root
    parent.addLinkedList(value)