【问题标题】:Error when making my own stack [duplicate]制作我自己的堆栈时出错[重复]
【发布时间】:2016-07-28 07:34:49
【问题描述】:

所以为了学习 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())

但是我收到了这个错误:

Traceback(最近一次调用最后一次):

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

TypeError: push() 接受 1 个位置参数,但给出了 2 个 [Finished in 0.092s]

【问题讨论】:

  • 所有方法都需要self 参数。
  • 变量self 没有神奇地引入。您必须通过将方法签名更改为 def push(self, object): 来定义它

标签: python


【解决方案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

【讨论】:

    猜你喜欢
    • 2015-05-25
    • 2015-06-18
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 2020-09-12
    • 2012-05-21
    相关资源
    最近更新 更多