【Pthon error】AttributeError: ‘Stack‘ object has no attribute ‘stack‘

今天继续在学数据结构,跟着教程一个个敲代码的时候,以下代码出现错误:

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()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值