Akash Shetty
Akash Shetty

Reputation: 1

How does attributes and class variables of a particular class initialize when instantiated in another class?

Learning Data structures from freecodecamp. Link to the video: https://www.youtube.com/watch?v=8hly31xKli0&t=10115s While implementing the Linked list...

Focus on the size() and search() methods that are defined under LinkedList class in the code below. We are declaring a pointer "current" assigning it to self.head attribute (current = self.head).

Then we observe "current.next_node". "next_node" is a class variable of class "Node". We instantiate the "Node" class under add() method and we use "next_node" with the object which completely makes sense since "Node" is instantiated under add() method.

But how come we are able to use the "next_node" variable inside size() and search() methods where "Node" class is not instantiated? What is the implication? We can use the attributes of a class under different class methods just by instantiating once in a method?

Please let me know what's happening...

class Node:
    data = None #Contains Node data
    next_node = None    #Contains reference to next node

    def __init__(self,data):
        self.data = data    

    def __repr__(self):
        return "<Node data: {0}>".format(str(self.data))

class LinkedList:
    def __init__(self):
        self.head = None

    def add(self,data):
        new_node = Node(data)
        new_node.next_node = self.head
        self.head = new_node

    def size(self):
        count = 0
        current = self.head
        print(current)

        while current:
            count += 1
            current = current.next_node
            print(current)

        return count

    def search(self,key):
       
        current = self.head     
        while current:
            if current.data == key:
                return current
            
            else:
                current = current.next_node
                print(current) 

        return None


    def __repr__(self):
        nodes = []
        current = self.head

        while current:
            nodes.append(str(current.data))
            current = current.next_node

        return "->".join(nodes)

Upvotes: 0

Views: 34

Answers (0)

Related Questions