制作自己的s时出错

2024-05-16 02:42:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是我的密码:

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 (most recent call last):

File "mypath/arrayStack.py", line 29, in abs.push('HI')

TypeError: push() takes 1 positional argument but 2 were given [Finished in 0.092s]


Tags: theselfreturnifstack堆栈defnot
1条回答
网友
1楼 · 发布于 2024-05-16 02:42:19

缺少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

相关问题 更多 >