制作自己的堆栈时出错

时间:2016-04-07 12:14:10

标签: python

因此,对于学习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.092秒内完成]

1 个答案:

答案 0 :(得分:1)

您缺少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
相关问题