2016-03-06 46 views
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。

你能幫我解決嗎?

+0

爲什麼你在這裏使用繼承?兩個堆棧不應該是同一個類的實例嗎? – jonrsharpe

回答

2

Python在父類初始化程序(Stack1.__init__)未被派生類自動調用的方式中頗爲獨特;你需要確保它自己:

class Stack2(Stack1): 
    def __init__(self): 
     super().__init__() # call the __init__ method of the super class 
     self.stack2 = []   

順便說一句,你不繼承只有1變量,你繼承所有父類的,你沒有在孩子重寫的行爲。

+0

謝謝。這是一個學習點。 – Sourav