Alexis
Alexis

Reputation: 127

NameError: name "AnyName" is not defined

I am trying to do an N-Ary tree based on Linked-Lists and Nodes. But whenever I try to add a new value to the tree I keep getting:

NameError: name 'self' is not defined

I work with modules so I have to import the classes from other files.

I get this error in def addTree(self, value, parent = self.root): on Tree Code

Tree Code

from Resources.LinkedList import *

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

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

Node Code

from Resources.LinkedList import *

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

Linked-List Code

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

Also thanks for your help, I'm kinda new to Python and I don't know what I am doing wrong.

Upvotes: 2

Views: 448

Answers (1)

eyllanesc
eyllanesc

Reputation: 243965

The problem is that "self" is only defined within the method and cannot be used in the arguments, the trick in these cases is to use None as an argument and make the verification:

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

Upvotes: 2

Related Questions