I am trying to create two types of stacks in python (LIFO technology). One of which (Stack master class) is a boilerplate stack class and the other (CountingStack class) inherits from the master class, but also has a method to count pop() calls.
However, when instantiating an object of CountingStack class, it doesn't seem to inherit the "__stk" attribute in the master class. This list is the actual container itself which acts as the stack.
The error I get is:
Traceback (most recent call last):
File "main.py", line 31, in <module>
stk.pop()
File "main.py", line 24, in pop
self.__stk.pop()
AttributeError: 'CountingStack' object has no attribute '_CountingStack__stk'
And my script is below:
class Stack:
def __init__(self):
self.__stk = []
def push(self, val):
self.__stk.append(val)
def pop(self):
val = self.__stk[-1]
del self.__stk[-1]
return val
class CountingStack(Stack):
def __init__(self):
Stack.__init__(self)
self.__pop_counter__ = 0
self.__push_counter__ = 0
def get_counter(self):
return self.__pop_counter__
def pop(self):
self.__stk.pop()
self.__pop_counter__ += 1
stk = CountingStack()
for i in range(100):
stk.push(i)
stk.pop()
print(stk.get_counter())
I am honestly not sure why the script is looking for an attribute called "_CountingStack__stk" other than it being a generated attribute of the subclass as a result of inheritance.
Thanks in advance!