Need help with classes/inheritance


Joined
Feb 7, 2011
Messages
1
Reaction score
0
This is the error I am getting:
Traceback (most recent call last):
File "C:\Users\Ma\Desktop\CS\cs173\calc.py", line 19, in <module>
main()
File "C:\Users\Ma\Desktop\CS\cs173\calc.py", line 17, in main
print(calc.top())
File "C:\Users\Ma\Desktop\CS\cs173\RPN.py", line 36, in top
return self._calcStack.top()
AttributeError: Stack instance has no attribute '__len__'

this is my code:
import RPN

def main():
calc = RPN.RPNCalculator()
RPNexpression = str(input("Enter RPN expression in string form and spaces between each number/operand: "))
print(RPNexpression)
RPNList = RPNexpression.split()
print(RPNList)
for i in RPNList:
calc.push(i)
print(calc.top())

import stack

class RPNCalculator(stack.Stack):

def __init__(self):
self._calcStack = stack.Stack()

def push(self, operand):
if operand == '+':
self.add()
elif operand == '-':
self.subtract()
elif operand == '*':
self.multiply()
elif operand == '/':
self.divide()
else:
self._calcStack.push(int(operand))

def top(self):
return self._calcStack.top()

def add(self):
try:
num2 = self._calcStack.pop()
num1 = self._calcStack.pop()
newSum = num1 + num2
self._calcStack.push(newSum)
except RuntimeError:
pass

def subtract(self):
try:
num2 = self._calcStack.pop()
num1 = self._calcStack.pop()
newSum = num1 - num2
self._calcStack.push(newSum)
except RuntimeError:
pass

def multiply(self):
try:
num2 = self._calcStack.pop()
num1 = self._calcStack.pop()
newSum = num1 * num2
self._calcStack.push(newSum)
except RuntimeError:
pass

def divide(self):
if self._calcStack.top() == 0:
raise ArithmeticError
try:
num2 = self._calcStack.pop()
num1 = self._calcStack.pop()
newSum = num1 / num2
self._calcStack.push(newSum)
except RuntimeError:
pass


class Stack:

def __init__(self):
self._stack = []

def top(self):
return self._stack[len(self._stack)-1]

def push(self, item):
self._stack.append(item)

def pop(self):
return self._stack.pop()

def isEmpty(self):
if len(self._stack) != 0:
return False
return True

def __len__(self):
return len(self._stack)

These are all separate python files but i imported them correctly. I really am at a loss because the error seems to have nothing to do with the code the error is pointing to. Sorry about indenting I don't know how to preserve it in forum posts but I can 100% guarantee you indenting is correct.
 
Last edited:
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top