今天继续在学数据结构,跟着教程一个个敲代码的时候,以下代码出现错误:
class Stack:
def __int__(self):
self.stack = []
def push(self, element):
self.stack.append(element)
def pop(self):
if len(self.stack) > 0:
self.pop()
else:
print("there is not elements in the stack")
def get_top(self):
if len(self.stack) > 0:
return self.stack[-1]
else:
print("there is not elements in the stack")
stack = Stack()
stack.push(1)
stack.push(3)
stack.push(4)
print(stack.pop())
stack.get_top()
报错
D:\D_Learning\PythonFile\venv\Scripts\python.exe D:\D_Learning\PythonFile\stack.py
Traceback (most recent call last):
File "D:\D_Learning\PythonFile\stack.py", line 22, in <module>
stack.push(1)
File "D:\D_Learning\PythonFile\stack.py", line 6, in push
self.stack.append(element)
^^^^^^^^^^
AttributeError: 'Stack' object has no attribute 'stack'
Process finished with exit code 1
网上源代码
这个是跟着视频一步一步敲的,按理来说不应该出错,目前还没有解决,写个博客记录一下!
代码更正:
class Stack:
def __init__(self):
self.stack = []
def push(self, element):
self.stack.append(element)
def pop(self):
if len(self.stack) > 0:
return self.stack.pop()
else:
print("there is not elements in the stack")
def get_top(self):
if len(self.stack) > 0:
return self.stack[-1]
else:
print("there is not elements in the stack")
stack = Stack()
stack.push(1)
stack.push(3)
stack.push(4)
print(stack.pop())
stack.get_top()