0

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

10 Comments

You are welcome. The core of your answer is correct but you should pay more attention to case (Python is case-sensitive).
@Wolf, I'll always remember your advice.
@jacobdavis, yes and when whil cur is None we exit from while-loop
@jacobdavis, Node("head") or Node() or Node(None) you pass "head" , "" , None for self.value of instance of Node class. you can send any but better if you send string in all of your programs send a string is better you keep routine in all your programs.
@jacobdavis, no you can not remove it, for the first node we set it None but for other Nodes, we set this to a reference other Nodes, do you know about Linked List in this code we create a stack with Linked List, see these linkes maybe help you: geeksforgeeks.org/linked-list-set-1-introduction, geeksforgeeks.org/stack-in-python
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.