没有属性“推”我是一个绝对的初学者使用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)它为什么说属性推?这不是一个属性,而是一种方法。
我有感觉,我失去了一些东西在这里:( 感谢您帮助我:>
非常感谢!我没有想到这个,现在它工作:) – Lorayne