Skip to content

Classes, instance state, and special methods [ref]

Problem

  • Construct a node storing 5 and a next reference of None.
  • Define a stack with push and top, then push and read 7.
  • Define __len__ for an object storing size 3.
  • Instantiate a nested Node class through an outer instance.
  • Verify that two stack instances do not share their lists.

Python solution

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

node = Node(5)
(node.val, node.next)  # (5, None)

class Stack:
    def __init__(self):
        self.values = []
    def push(self, value):
        self.values.append(value)
    def top(self):
        return self.values[-1]

stack = Stack()
stack.push(7)
stack.top()  # 7

class Sized:
    def __init__(self, size):
        self.size = size
    def __len__(self):
        return self.size

len(Sized(3))  # 3

class Tree:
    class Node:
        def __init__(self, key):
            self.key = key
    def make_node(self, key):
        return self.Node(key)

Tree().make_node(9).key  # 9

a, b = Stack(), Stack()
a.push(1)
(a.values, b.values)  # ([1], [])