0
我想從父類繼承變量到子類。但是,我正面臨屬性錯誤。請在下面找到我的代碼: -繼承時出現屬性錯誤
class Stack1(object):
def __init__(self):
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)
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):
self.stack2 = []
def push(self):
#popped_value = Stack1.pop(self)
#popped_value = super(Stack2, self).pop()
super(Stack2, self).pop()
print("popped_value child", self.popped_value)
self.stack2.append(popped_value)
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)
first_stack = Stack1()
second_stack = Stack2()
first_stack.push(1)
first_stack.push(2)
first_stack.display()
print("Pushed above items into stack1")
first_stack.pop()
second_stack.push()
second_stack.display()
print("Pushed above items into stack2")
first_stack.pop()
second_stack.push()
second_stack.display()
print("Pushed above items into stack2")
下面是錯誤: -
E:\>python dsq.py
[1, 2]
Pushed above items into stack1
popped_value parent 2
Traceback (most recent call last):
File "dsq.py", line 56, in <module>
second_stack.push()
File "dsq.py", line 30, in push
super(Stack2, self).pop1()
File "dsq.py", line 8, in pop1
self.popped_value = self.stack1.pop()
AttributeError: 'Stack2' object has no attribute 'stack1'
在這裏,我想實現使用兩個堆棧隊列。所以,我試圖將彈出的物品從第一個堆棧推到第二個堆棧。所以,爲了實現這一點,我需要從第一個堆棧訪問popped_item到我的子類Stack2。
你能幫我解決嗎?
爲什麼你在這裏使用繼承?兩個堆棧不應該是同一個類的實例嗎? – jonrsharpe