Search code examples
pythonlinked-listsingly-linked-list

Why is it necessary to enter the object twice for a class?


I am just getting started with linked lists, and I wrote some basic functions with a linked list class and node objects. When calling a function, it seems that I have to enter in the linked list object twice and I think I'm doing something wrong. To add a new node with value "b" to the tail, I have to call sample_list.add_tail_node(sample_list, "b"), when I think it is supposed to be sample_list.add_tail_node("b"), because what is the point of specifying sample_list twice

class LinkedList:

def __init__(self):
    self.head = None

def add_tail_node(self, val: int):
    node = self.head
    while True:
        if node.next is None:
            node.next = Node(val)
            break
        node = node.next

class Node:
def __init__(self, val):
    self.val = val
    self.next = None
sample_list = LinkedList
sample_list.head = Node("a")
sample_list.add_tail_node(sample_list, "b")

Solution

  • You are assigning class reference to a variable here

    sample_list = LinkedList
    

    When you need to call a class, so it creates a instance

    sample_list = LinkedList()
    
    For better undersanding

    When you are calling

    sample_list.head = Node("a")
    

    You are actualy assigning head to a class itself

    And when you are calling object method using class, you need to provide class object instance variable first (self value), which is suited automatically when calling method from instance object

    sample_list.add_tail_node(sample_list, "b")
    

    This will actually process add_tail_node method on a class itself, not it's instance