我正在尝试使用两个堆栈创建一个队列,下面是我的代码: -
class Stack1(object):
def __init__(self):
super(Stack1, self).__init__()
self.stack1 = []
def push(self, item):
self.stack1.append(item)
def pop(self):
self.popped_value = self.stack1.pop()
print("popped_value parent", self.popped_value)
return self.popped_value
def peek(self):
try:
return self.stack1[len(stack1)-1]
except:
print("Cannot peek into stack 1")
def is_empty(self):
if len(self.stack1) == 0:
return True
else:
return False
def display(self):
print(self.stack1)
class Stack2(Stack1):
def __init__(self):
super(Stack2).__init__()
self.stack2 = []
def push(self, popped):
self.popped = popped
return self.stack2.append(self.popped)
def pop(self):
return self.stack2.pop()
def peek(self):
try:
return self.stack2[len(stack2)-1]
except:
print("Cannot peek into stack 2")
def is_empty(self):
if len(self.stack2) == 0:
return True
else:
return False
def display(self):
print(self.stack2)
class DoubleStackQueue(Stack2):
def __init__(self):
super(DoubleStackQueue, self).__init__()
pass
def enqueue(self, item):
self.item = item
super(DoubleStackQueue, self).push(self.item)
Stack1.push(self.item)
dsq = DoubleStackQueue()
dsq.enqueue(2)
这里,我试图通过访问类Stack1的push()方法将项目推送到stack1。但是,我收到以下错误: -
E:\>python dsq.py
Traceback (most recent call last):
File "dsq.py", line 78, in <module>
dsq.enqueue(2)
File "dsq.py", line 75, in enqueue
Stack1.push(self.item)
TypeError: push() missing 1 required positional argument: 'item'
你能帮帮我吗?
答案 0 :(得分:1)
当你直接从课堂调用实例方法时,就像调用Stack1.push
一样,你需要明确提供self
参数:
Stack1.push(self, self.item)
在您的电话Stack1.push(self.item)
中,self.item
作为self
参数传递,并且解释程序引发错误,因为它缺少其他所需的位置参数item
。
或者使用super
:
super(Stack2, self).push(self.item)
这说:
Stack2.push
方法应该负责调用Stack1.push
,以便DoubleEndedQueue
无需执行双重调用。super(DoubleEndedQueue, self).push(self.item)
替换self.push.item
...因为DoubleEndedQueue
没有定义push
方法,所以会检查超类Stack2
自动。