LismUK
LismUK

Reputation: 119

Creating python objects of same type from nested class

My List class has a nested _Node class within it. With these 2 classes, I can:

I can't, however, initialize a _Node within a _Node. The last line of the code is below causes NameError: global name '_Node' is not defined

class List:
    def __init__(self):
        self.root = None
        self.brother = None

    def set_root(self):
        self.root = self._Node()

    def set_brother(self):
        self.brother = List()

    def set_root_next(self):
        self.root.set_next()

    class _Node:
        def __init__(self, next_node=None, data=None):
            self.next_node = next_node
            self.data = data

        def set_next(self):
            self.next_node = _Node()

if __name__ == '__main__':
    x = List()
    x.set_root()
    x.set_brother()
    x.set_root_next()

How do I solve this? Making the _Node class unnested works but I am planning to have many types of list in the same file. All accompanying nodes will inherit from a single abstract class so keeping this structure is important.

Upvotes: 0

Views: 430

Answers (1)

farghal
farghal

Reputation: 301

Try using self.__class__() instead

class List:
    def __init__(self):
        self.root = None
        self.brother = None

    def set_root(self):
        self.root = self._Node()

    def set_brother(self):
        self.brother = List()

    def set_root_next(self):
        self.root.set_next()

    class _Node:
        def __init__(self, next_node=None, data=None):
            self.next_node = next_node
            self.data = data

        def set_next(self):
            self.next_node = self.__class__()

if __name__ == '__main__':
     x = List()
     x.set_root()
     x.set_brother()
     x.set_root_next()

Upvotes: 2

Related Questions