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