Search code examples
pythonpython-3.xoopinstance-variables

Instance variables in another class (no single inheritance)


I want to know how to use an instance variable (class A) in class B. Here is a small code quote that runs normally:

class Node:
   def __init__(self, value):
      self.value = value
      self.next = None
 
class Stack:
   def __init__(self):
      self.head = Node("head")
      self.size = 0
   def __str__(self):
      cur = self.head.next
      out = ""
      while cur:
         out += str(cur.value) + "->"
         cur = cur.next
      return out[:-3] 

I wonder how I can use instance variables (.next and .value) in the class Stack. I think instance variables (.next and .value) can appear and be used only in Node class. As I know, we should use single inheritance and class Stack should change to class Stack(Node). Also, I don't understand what while cur means. Is it the same as while True?

Could you explain this problem for me?


Solution

  • Question_1 : how I can use instance variables (.next and .value) in the class Stack. I think instance variables (.next and .value) can appear and be used only in Node class. As I know, we should use single inheritance and class Stack should change to class Stack(Node)?

    Answer_1 : in def ___init__ we create variable of Node then we can use .next and .value of self.head because this variable is instance of Node class.

    Question_2 : Also, I don't understand what while cur means. Is it the same as while True?

    Answer_2 : for first Node we set .next = None then when we have multiple nodes we run on nodes until get Node.next == None then None assign to cur and we exit from while-loop when cur will be None.