Home > Back-end >  Does order of methods within a class matter?
Does order of methods within a class matter?

Time:11-17

My problems or rather my misunderstanding are next.

First one:

Basically i made my linked list class, and now as you can see in following code in constructor i called append method before it was actually created and the code run without an error, so i am really interested to know why i didn't encountered any error there.

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None


class Linkedlist:
    def __init__(self, *value):
        if len(value) == 1:
            new_node = Node(value[0])
            self.head = new_node
            self.tail = new_node
            self.lenght = 1
        else:
            self.__init__(value[0])
            other_values = value[1::]
            for i in other_values:
                self.append(i)
        print('test1')


    def append(self, *value):
        for i in value:
            new_node = Node(i)
            if self.head == None:
                self.head = new_node
                self.tail = new_node
            else:
                self.tail.next = new_node
                self.tail = new_node
                self.lenght  = 1
            print('test2')

        return True

Second one:

As you can see i left print function in both constructor and append method in order to see how things are going. when i execute next code:

my_linked_list = Linkedlist(3, 2, 7, 9)

i get the output as following: test1, test2, test2, test2, test1 and i was expecting only test2, test2, test2, test1, i am curious why does it print test1 first.

Sorry if my question was too long. I am quite new to programming and really curious about a lot of things. Answer would be greatly appreciated.

CodePudding user response:

Functions being defined is different from them being run; in your code, you define __init__ before you define append, but you don't actually call append until later. By the time you call it, it's been defined.

For the order of prints, __init__ is called implicitly when you create the LinkedList.

CodePudding user response:

Your definition of Linkedlist.__init__ includes a recursive call to Likedlist.__init__. You don't need that, nor do you need to treat a single argument as a special case. You can simply write

def __init__(self, *values):
    self.length = 0

    for v in values:
        self.append(v)

You'll need to adjust append slightly to ensure that self.length is always incremented, even if the list was originally empty.

append becomes even simpler if you define your list to always include a dummy node that self.head references. You can store the length in this node.

def __init__(self, *values):
    self.head = self.tail = Node(0)
    for v in values:
        self.append(v)

I leave it as an exercise to write append under this assumption.

  • Related