制作自己的堆栈时出错



因此,为了学习python和一般的一些数据结构,我首先要创建一个Stack。这是一个简单的基于数组的堆栈。

这是我的代码:

class ArrayBasedStack:
    'Class for an array-based stack implementation'
    def __init__(self):
        self.stackArray = []
    def pop():
        if not isEmpty():
            # pop the stack array at the end
            obj = self.stackArray.pop()
            return obj
        else:
            print('Stack is empty!')
            return None
    def push(object):
        # push to stack array
        self.stackArray.append(object)
    def isEmpty():
        if not self.stackArray: return True
        else: return False
'''
    Testing the array-based stack
'''
abs = ArrayBasedStack()
abs.push('HI')
print(abs.pop())

但我得到了这个错误:

追踪(最近一次通话):

文件"mypath/arrayStack.py",第29行,在abs.push('HI')中

TypeError:push()接受1个位置参数,但给出了2个[在0.092s内完成]

您缺少self参数。

self是对对象的引用。这与许多C风格的语言中的概念非常接近。

所以你可以这样修复。

class ArrayBasedStack:
    'Class for an array-based stack implementation'
    def __init__(self):
        self.stackArray = []
    def pop(self):
        if not self.isEmpty():
            # pop the stack array at the end
            obj = self.stackArray.pop()
            return obj
        else:
            print('Stack is empty!')
            return None
    def push(self, object):
        # push to stack array
        self.stackArray.append(object)
    def isEmpty(self):
        if not self.stackArray: return True
        else: return False
'''
    Testing the array-based stack
'''
abs = ArrayBasedStack()
abs.push('HI')
print(abs.pop())

输出:

HI

最新更新