2017-05-24 60 views
0

没有属性“推”我是一个绝对的初学者使用Python和一般不编码还非常好,所以希望我的代码是不是太可笑:d的Python:“海峡”对象在PyCharm

我需要编写一个堆栈程序,其中堆栈程序是一个列表。 这是我的代码:

class Stack: 
    def __init__(self): 
     self.items = [] 

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

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

    def isEmpty(self): 
     return self.items == [] 

def execute(list): 
    result = Stack() 
    for x in list: 
     if 'LOAD' in x: 
      number = substring_after(x, " ") 
      result.push(number) 
     elif 'ADD' in x: 
      result = result.pop() + result.pop() 
     elif 'MUL' in x: 
      result = result.pop() * result.pop() 
     elif 'SUB' in x: 
      first = result.pop() 
      result = result.pop() - first 
     elif 'DIV' in x: 
      first = result.pop() 
      result = result.pop()/first 
     elif 'PRINT' in x: 
      print(result.pop()) 
      if result.isEmpty(): 
       print('Execution completed') 
      else: 
       print('There are still values in the Stack') 
     else: 
      print('Not a valid statement for Stack Program') 

def substring_after(s, delim): 
    return s.partition(delim)[2] 

def main(): 
    operation1 = ["LOAD 2", "LOAD 3", "ADD", "LOAD 4", "MUL", "PRINT"] 
    operation2 = ["LOAD 4", "LOAD 5", "ADD", "LOAD 2", "LOAD 3", "ADD", 
    "MUL", "PRINT"] 
    operation3 = ["LOAD 6", "LOAD 7", "LOAD 4", "SUB", "DIV", "LOAD 5", 
    "MUL", "PRINT"] 

    execute(operation1) 

if __name__ == '__main__': 
    main() 

我得到的错误是:

Traceback (most recent call last): 
    File "XXX/EA2-Stack.py", line 53, in <module> main() 
    File "XXX/EA2-Stack.py", line 47, in main execute(operation1) 
    File "XXX/EA2-Stack.py", line 19, in execute result.push(number) 
AttributeError: 'str' object has no attribute 'push' 

我不明白:

1)为什么它说,没有'推'?我定义了一个叫做'push'的方法。 我也试着写: 推(结果数),但后来它说:“未解决的参考”

2)它为什么说属性推?这不是一个属性,而是一种方法。

我有感觉,我失去了一些东西在这里:( 感谢您帮助我:>

回答

2
result = Stack() 
result.push(number) 

这里没有问题

result = result.pop() + result.pop() 
result.push(number) 

现在有一个问题! result现在是一个str(如错误消息所示)而不是Stack,实际上str没有必要的属性。使用单独的变量名。是,result.push是一个attrib尽管这也是一种方法。

+0

非常感谢!我没有想到这个,现在它工作:) – Lorayne

0

为什么说,没有'推'?

因为你不在栈实例上调用它。第一个命令执行后,result不再指向堆栈实例。

为什么说属性推?这不是一个属性,而是一种方法。

Python解释器并不关心。首先检查是否存在具有该名称的属性。之后它会尝试调用它。在Python中,函数(因此方法)是一等公民,没有什么特别的。

0

您从Stack对象重新分配你的结果变量的值,从而破坏您的堆栈对象:

result = result.pop() + result.pop() 

这破坏了你的筹码()的实例

相关问题