teuber789
teuber789

Reputation: 1637

Python - inner class is not defined?

I have to do an unrolled linked list for one of my classes. I'm new to python, but not to programming, and for some reason I cannot get around this little problem!

I have a class Node that is to be the node object used within the unrolled linked list. The unrolled linked list class performs all the operations on the Node class.

class UnrolledLinkedList(object):

    """ INNER NODE CLASS """
    class Node(object):
        def __init__(self):
            self.array = []
            self.next_node = None
    """ END NODE CLASS """

    def __init__(self, max_node_capacity=16):
        self.max_node_capacity = max_node_capacity
        self.head = Node()


    """ OTHER FUNCTIONS OF UNROLLEDLINKEDLIST CLASS """

The problem comes at the last line of the UnrolledLinkedList class' init function: "global name Node is not defined". I double checked my indentation and looked all over the internet for examples of something like this, but couldn't find any. Would someone mind explaining to me what's wrong?

Upvotes: 14

Views: 8145

Answers (4)

Mike Müller
Mike Müller

Reputation: 85532

Use:

self.head = self.Node()

and it works.

A class does not create its own name space. Using self.Node(), Python first searches all attributes of the instances. Since it does not find the name Node there, it it searches the class UnrolledLinkedList for Node.

Alternatively, you can use the class name directly:

UnrolledLinkedList.Node()

You can achieve the same without nesting the class Node:

class Node(object):
    def __init__(self):
        self.array = []
        self.next_node = None

class UnrolledLinkedList(object):
    def __init__(self, max_node_capacity=16):
        self.max_node_capacity = max_node_capacity
        self.head = Node()

Upvotes: 2

scooter me fecit
scooter me fecit

Reputation: 1063

Qualify Node() with self:

class UnrolledLinkedList(object):
    class Node(object):
        def __init__(self):
            self.array = []
            self.next_node = None

def __init__(self, max_node_capacity=16):
    self.max_node_capacity = max_node_capacity
    self.head = self.Node()

Python needs to qualify references to things. In this case, you could either say UnrolledLinkedList.Node() or self.Node().

Upvotes: 0

gnerkus
gnerkus

Reputation: 12037

The inner class Node is a member of the class UnrolledLinkedList and can only be accessed via self.

def __init__(self, max_node_capacity=16):
    self.max_node_capacity = max_node_capacity
    self.head = self.Node()

Upvotes: 9

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799210

Methods do not include their class as a scope to be searched. If you want this to work then you will need to use either UnrolledLinkedList.Node or self.Node instead.

Upvotes: 16

Related Questions