Python 创建自己的堆栈时出错
为了学习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
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):