2017-10-11 141 views
0

我试图通过重用CalculatorEngine类来获得RPN计算器,如下所示。但是当我运行它时,它显示一个属性错误:'RPNCalculator'对象没有属性'dataStack'。我该如何解决这个问题? (我没有包括Stack类,因为想太多代码。)Python:RPN计算器

 class CalculatorEngine(object): 
     def __init__(self): 
      self.dataStack = Stack() 

     def pushOperand(self, value): 
      self.dataStack.push(value) 

     def currentOperand(self): 
      return self.dataStack.top() 

     def performBinary(self, fun): 
      right = self.dataStack.pop() 
      left = self.dataStack.top() 
      self.dataStack.push(fun(left, right)) 

     def doAddition(self): 
      self.performBinary(lambda x, y: x + y) 

     def doSubtraction(self): 
      self.performBinary(lambda x, y: x - y) 

     def doMultiplication(self): 
      self.performBinary(lambda x, y: x * y) 

     def doDivision(self): 
      try: 
       self.performBinary(lambda x, y: x/y) 
      except ZeroDivisionError: 
       print("divide by 0!") 
       exit(1) 

     def doTextOp(self, op): 
      if (op == '+'): 
       self.doAddition() 
      elif (op == '-'): 
       self.doSubtraction() 
      elif (op == '*'): 
       self.doMultiplication() 
      elif (op == '/'): self.doDivision() 


    class RPNCalculator(CalculatorEngine): 
     def __init__(self): 
      super(CalculatorEngine, self).__init__() 

     def eval(self, line): 
      op = line.split(" ") 
      try: 
       for item in op: 
       if item in '+-*/': 
        self.doTextOp(item) 
       elif item in '%': 
        self.performBinary(lambda x, y: x % y) 
       else: 
        self.pushOperand(int(item)) 
       return self.currentOperand() 
      except ZeroDivisionError: 
       print 'divide by 0!' 
+0

代码的其余部分(实例创建和操作,当然还有生成异常的行)在哪里?另外,修复缩进。 – CristiFati

+0

https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – jdv

回答

0

class X(object): 
 
    def __init__(self, name): 
 
    self._name = name 
 

 
    def doit(self, bar): 
 
    print("Hello") 
 

 
class Y(X): 
 
    def __init__(self): 
 
    # super(X, self).__init__() 
 
    X.__init__(self, "DDXX") 
 

 

 
i = X("Yuze") 
 
j = Y()

或者你可以用这个片段来解决它。

+0

是的,我做到了。我没有添加代码,因为它不会允许我发布:) – Tiffy

+0

这既不是答案,也不是正确的。 – CristiFati

+0

我明白了。我认为这是因为超类的使用。我建议使用这个链接的方法https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods –