Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建自己的堆栈时出错_Python - Fatal编程技术网

Python 创建自己的堆栈时出错

Python 创建自己的堆栈时出错,python,Python,为了学习python和一般的一些数据结构,我首先创建了一个堆栈。这是一个简单的基于数组的堆栈 这是我的密码: class ArrayBasedStack: 'Class for an array-based stack implementation' def __init__(self): self.stackArray = [] def pop(): if not isEmpty(): # pop the st

为了学习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())
但我得到了一个错误:

回溯(最近一次呼叫最后一次):

文件“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

在所有方法上都需要
self
参数。变量
self
不是神奇地引入的。您必须通过将方法签名更改为
def push(self,object):